MeloS
MeloS

Reputation: 7938

Swift: what's the difference between Array<OtherModule.MyType>() and [OtherModule.MyType]()

I'm using a type from a different module, let's call it OtherModule.MyType,

This code:

var a = [OtherModule.MyType]() 

will produce an error invalid use of '()' to call a value of non-function type '[MyType.Type]'

This code won't:

var ax = [OtherModule.MyType]

But I believe ax is not an array any more, since this code

ax.append(OtherModule.MyType())

will cause an error Cannot invoke 'append' with an argument list of '(MyType)'

So I wonder what ax really is?

Besides, this code works fine:

var ay = Array<OtherModule.MyType>()
ay.append(OtherModule.MyType())

UPDATE: I'm using swift 1.2 with Xcode 6.3

Upvotes: 0

Views: 98

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

For some reason best known to the Swift team (modules are very scantly documented), Module.Thing behaves differently to Thing.

While Int is just a type name:

let i: Int = 1  // fine
// not fine, "expected member name or constructor call after type name"
let j = Int     

Swift.Int can be both:

// used as a type name
let k: Swift.Int = 1
let t = Swift.Int.self

// but also used as a value
let x = Swift.Int
// equivalent to this
let y = Int.self
toString(x) == toString(y) // true

Under some uses it only wants to be a value, not a type name though. Hence this works:

// a will be of type [Int.Type], initialized with an array
// literal of 1 element, the Int metatype
let a = [Swift.Int]

But trying to use it as a type name in this context fails: [Swift.Int]() is no more valid than writing [1]() or let strs = ["fred"]; strs().

This behaviour seems a little arbitrary, and may even be a bug/unintentional.

Since the only way in which Swift.Int can be used in this context:

Array<Swift.Int>() 

is as a type not a value (since only types can go between the angle brackets), it kind of makes sense that this works while the more ambiguous array literal syntax behaves differently.

Upvotes: 1

Related Questions