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 = []
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.
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.
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).
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>
You can do this
let blankArray = [String]()
or ny other type you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With