arty
arty

Reputation: 11

Defining arrays in Swift

Just got a quick array question it might be a little stupid but im kind of new to coding, what is the difference between the code here:

var items:[String]

so from my understanding here you are defining the variable 'items' as an empty array string. items is of type array

var items: [String] = ()

here you are defining items as an empty array but shouldn't it written as:

 var items = [String]() 

or is this essentially the same code

Upvotes: 1

Views: 154

Answers (2)

Daniel Hall
Daniel Hall

Reputation: 13679

This:

var items:[String]

means that you are declaring a variable named items that will be an array of String instances. However, you are not initializing that variable to any initial value. The compiler will not let you use this variable before it is initialized with a value, because you are not declaring the type ([String]) to be optional ([String]?), so it must be initialized and contain a non-nil value to be used by your code.

This:

var items: [String] = ()

means that you are declaring a variable named items that should be an array of String instances, but you are trying to initialized it with the value (), which in Swift is synonymous with Void. The compiler will not allow this. A similar, valid notation would be: var items: [String] = [] which uses an empty array of unspecified type ([]) to initialize the value. Since you declared items to be an array of String values, the compiler can infer that the untyped empty array ([]) should be an empty array of String values ([String]) and will allow it.

This:

var items = [String]()

is declaring a variable named items that you aren't explicitly specifying the type for, and immediately initializing it with an empty array of String values. From this, the compiler can infer the type of the variable is [String] so you don't need to declare it.

Upvotes: 4

Faris Sbahi
Faris Sbahi

Reputation: 666

var items = [String]() is called initializer syntax. It means you're allocating memory for the future storage of an array of strings.

However, by doing var items:[String] you are not providing an initializer. This will cause an error--consider conceptually that you are pointing to an area of memory that you have not allocated space for. There's nowhere for additional variables to go!

On the other hand, var items: [String] = () doesn't seem to be any kind of standard syntax. It seems like you're casting an array of strings as void. This shouldn't compile.

Upvotes: 0

Related Questions