Why can't you initialize an empty array in Swift?

This code works,

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

but this code does not work, for no apparent reason

 let people = [] 

and does not do this (volatility does not matter):

 var people = [] 

Error: "It is not possible to convert the type of an Array expression to the type" ArrayLiteralConvertible ", but this does not make any sense to me, but none other questions that appear in the search address for this question.

At first I thought that this was due to the type of output, but this is not a problem (at least not just like that!), Because although it works (with the specified type)

 var people:Array = [""] 

this is not the case (with the type specified above, but without the string specified inside the array):

 var people:Array = [] 

Since the last of these two has an explicitly specified type, it does not need the string passed inside the array.

Some languages ​​(weird!) Consider the type of a variable to indicate the type of an element inside an array, so I also tried to specify String instead of Array , but got the same results. This first one works, and the second one doesn't:

 var people:String = [""] 
 var people:String = [] 
+6
source share
2 answers

The syntax you are looking for is

 let people : [String] = [] 

or

 let people = [String]() 

in both cases, you can replace [String] with Array<String>

For this code

 let people = [] 

The compiler cannot understand the type of people . What type do you expect from this?

Note Array not a complete type because it requires a common part. The full type is similar to Array<String>

+10
source

You can do it

 let blankArray = [String]() 

or any other type you need.

+2
source

Source: https://habr.com/ru/post/976181/


All Articles