1

As I know in Swift, arrays are typed. Items of array must be in same type and if you didn't write the type of array in initialize, compiler will infer it based on initial values.

But I tried to initialize array withe different types and the compiler didn't give any error and can deal with array without any issues !!! Can anyone explain to me what is going on?

enter image description here

0

1 Answer 1

1

Since Swift compiler is smart enough to deduce the closest common subtype of array initializer expressions, your array element type ends up an NSObject.

Here is a quote from the Swift book:

The final snippet creates a constant array called library, which contains two Movie instances and three Song instances. The type of the library array is inferred by initializing it with the contents of an array literal. Swift’s type checker is able to deduce that Movie and Song have a common superclass of MediaItem, and so it infers a type of [MediaItem] for the library array:

let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.