Kyle
Kyle

Reputation: 4449

What's the difference between [Int] & Array<Int>?

let numberList = Array(1...10) // type == Array<Int>
let numberList2 = [1,2,3,4,5,6,7,8,9,10] // type == [Int]

The code above assigns the commented types to each constant. I don't recall running into an explanation for this in the documentation.

Is it simply a case of one using the constructor, and the other using literal notation, and as a result the differing types are produced?

If so, are there any differences to using one over the other, once they've been declared? (i.e. using the constructor allows you to use class initializers etc. but post initialization, does one offer any benefits over the other?)

They seem to both use the same Array API once initialized. So I'm assuming this is all purely syntactical?

Lastly, is there any way to mimic the constructors functionality via the literal notation? e.g.

let arr = [](1...10) // doesn't create [1,2,3,4,5,6,7,8,9,10]

Somewhat Unrelated

Can anyone tell me why the following code produces the result it does?:

let numberList2 = [1...10] // == ["1..<11"]

I reason that the above is an array containing a range. The type shown in a Playground reports that the type is: [Range], as expected. However, why is the value seemingly reported as an array containing a string representing a half-open range up to 11, rather than a closed range up to 10?

Apologies for the disjointed post. Thanks in advance for any help.

Upvotes: 3

Views: 686

Answers (1)

user2864740
user2864740

Reputation: 61865

From The Swift Programming Language: Collection Types

Array Type Shorthand Syntax

The type of a Swift array is written in full as Array<SomeType>, where SomeType is the type of values the array is allowed to store. You can also write the type of an array in shorthand form as [SomeType]. Although the two forms are functionally identical, - the shorthand form is preferred and is used throughout this guide when referring to the type of an array.

That is, both comments are correct - and both represent the same type.

Upvotes: 8

Related Questions