Reputation: 57
I have been googling for a while and every tutorial taught me that to create an array, you just do the following:
var persons = [String]
But I am moving from swift code to iOS development learning material and everywhere it is now
var persons = [String]()
Why do we need those braces at the end?
Upvotes: 3
Views: 1709
Reputation: 3770
It seems like you're mixing up 2 concepts: variable declaration, and variable assignment.
To declare an empty Array in Swift, you have to explicitly state what Types the array can hold. You do this either with the long-hand definition:
var persons: Array<String>
Or the shorthand syntax (preferred):
var persons: [String]
Note the use of a colon ":" instead of equals "=".
Both of these are saying "I'm declaring the existence of a variable (not constant) called 'persons' which will be a mutable Array full of Strings. Right now it's undefined though."
In Obj-C, you can put any kind of Object into an NSArray, which means you can't really be sure what you'll get out of one. Declaring the Array contents in this way is one of Swift's Type safety features. You can be confident that persons
will only ever contain String
instances.
To assign a value to your variable, meaning that it doesn't just have a definition but also has a valid object assigned to it in memory, you have to actually initialize the Array:
var persons = [String]()
This is essentially a shorthand way to initialize an empty Array that will hold a certain Type, without passing any parameters to the init: method. After this, persons
actually has a value, which is a completely empty Array that is only allowed to contain Strings.
Alternatively, Swift's Array Type has a 2nd initializer that lets you pass parameters:
init(count: Int, repeatedValue: T)
You could use this to create an Array w/a set length and initial values:
let immutableBobsArray = Array(count: 3, repeatedValue: "Bob")
println(\(immutableBobsArray)) \\ ["Bob", "Bob", "Bob"]
See "Collection Types" in the Apple's Swift Programming Guide, and also the Array entry in the Swift Standard Library
Upvotes: 7
Reputation: 6777
[String]
is the name of a type in Swift. Specifically, it is the type Array<String>
, which is a parameterized version of the generic Array<T>
type. Just like the statement var number = Int
doesn't make any sense unless you explicitly tell the compiler that you are constructing an instance of a specific type.
What you want is either var persons = [String]()
, or, if you want to specify the initial value of your variable with an array literal, you can do var persons: [String] = []
. Note that in the second option we are forced to specify the type of our variable since Swift's type inference cannot figure out the type of an empty array (what values does []
hold?).
Upvotes: 4