简体   繁体   中英

Can an array be initialised with literals of different types in Swift?

As per the Swift document, if the type of an array is inferred from the array literals. Now I am getting confused that if you assign an Int , String and Double values for an array there are no errors being thrown.

**在此处输入图片说明**

Try the same code here on an online Swift compile` or an Xcode with version 6.3.1 or 6.3.2. I have tried the above one on 6.4.

Now can anyone please tell me what will be the type of array?

And how come this array is allowing to initialise it with different data types?

Thank you.

Yes, you can make an array of Any :

var sample1: [Any] = [12,"Hello"]

This is almost always a mistake, though, which is why Swift requires you to explicitly show the type. The vast majority of things you would want to do (except parse JSON in Swift...) can be done without resorting to this kind of data structure.

For some kinds of arrays, you can use AnyObject rather than Any . This will require all of the elements to be "object-like" which is a little more specific than Any , and is more interoperable with ObjC:

var sample1: [AnyObject] = [12,"Hello"]

This is also almost always a mistake.

The error you're seeing is that Swift needs "more context." Since your objects do not share an obvious parent below AnyObject , Swift doesn't know if you really mean that, or if you made a mistake. In most cases, what you want here is an array of some protocol that all of the elements conform to instead.

It is possible but you should try to have your arrays of one data type. It minimizes possibilities for making errors.

So that is why you want to explicitly specify the type of the array to contain Any type of objects.

Your example becomes:

var array: [AnyObject] = [20, 4.0, ""]

Notice that I'm using AnyObject not just Any . The difference between the two is that AnyObject must be a class whereas Any can be just about anything (tuple, struct, ...).

When you make an array of equal types of objects such as:

var array = [20, 4, 8]

The compiler will be kind enough to infer the type for you. So the line above is semantically equal to:

var array: [Int] = [20, 4, 8]

If you need any additional info feel free to ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM