Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you not initialize an empty Array in Swift?

Tags:

swift

This code works,

let people = ["Tom","Dick","Harry"]

but this code doesn't work, for no apparent reason

let people = []

and nor does this (mutability matters not):

var people = []

The error is "Cannot convert expression's type Array to type 'ArrayLiteralConvertible'", but that makes no sense to me, and none of the other questions that show up in a search address this question.

At first I thought it had to do with type inference, but that proves not to be the issue (at least not simply that!) since although this works (with type specified)

var people:Array = [""]

this does not (with type specified as above but no String given inside the Array):

var people:Array = []

Since the last of these two has the type specified explicitly, it shouldn't need a String passed inside the Array.

Some languages (weirdly!) consider the type of the variable to refer to the type of item inside the array, so I also tried specifying String instead of Array, but got the same results. This first one works and the second doesn't:

var people:String = [""]
var people:String = []
like image 436
iconoclast Avatar asked Oct 02 '14 21:10

iconoclast


People also ask

How do you initialize an array to an empty array?

Array Initializer To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.

How do you declare an array in Swift?

We declare an array in Swift by using a list of values surrounded by square brackets. Line 1 shows how to explicitly declare an array of integers. Line 2 accomplishes the same thing as we initialize the array with value [1, 2] and Swift infers from that that it's an array of integers.

What is an empty array?

An empty array is an array of length zero; it has no elements: int[] emptyArray = new int[0]; (and can never have elements, because an array's length never changes after it's created).


2 Answers

The syntax you are looking for is

let people : [String] = []

or

let people = [String]()

in both case, you can substitute [String] with Array<String>

For this code

let people = []

It is impossible for compiler to figure it out the type of people. What type do you expect it have?

Note Array is not a complete type because it require the generic part. A complete type is like Array<String>

like image 69
Bryan Chen Avatar answered Sep 23 '22 17:09

Bryan Chen


You can do this

let blankArray = [String]()

or ny other type you need.

like image 40
Steve Rosenberg Avatar answered Sep 24 '22 17:09

Steve Rosenberg