I\'m really confused with the ways we create an array in Swift. Could you please tell me how many ways to create an empty array with some detail?
As per Swift 5
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
you can remove the array content with passing the array index or you can remove all
var array = [String]()
print(array)
array.append("MY NAME")
print(array)
array.removeFirst()
print(array)
array.append("MY NAME")
array.removeLast()
array.append("MY NAME1")
array.append("MY NAME2")
print(array)
array.removeAll()
print(array)
There are 2 major ways to create/intialize an array in swift.
var myArray = [Double]()
This would create an array of Doubles.
var myDoubles = [Double](count: 5, repeatedValue: 2.0)
This would create an array of 5 doubles, all initialized with the value of 2.0.
Compatible with: Xcode 6.0.1+
You can create an empty array by specifying the Element type of your array in the declaration.
For example:
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Example from the apple developer page (Array):
Hope this helps anyone stumbling onto this page.
You could use
var firstNames: [String] = []
Swift 5
There are three (3) ways to create a empty array in Swift and shorthand syntax way is always preferred.
Method 1: Shorthand Syntax
var arr = [Int]()
Method 2: Array Initializer
var arr = Array<Int>()
Method 3: Array with an Array Literal
var arr:[Int] = []
Method 4: Credit goes to @BallpointBen
var arr:Array<Int> = []