Empty array can be cast to array of any type

2020-03-13 06:42发布

问题:

It seems empty arrays in Swift can be cast to any array type.

See the following example:

var obj = [Int]()

// compiler warns that this cast always fails, but this evaluates to true
print(obj is [String]) 

obj.append(3)

// This evaluates to false as expected
print(obj is [String])

This is easily verifiable in a playground, but will also happen in compiled code. Is this a known issue?

回答1:

As @Hamish indicated, this is indeed a known issue. His comment points to bug report https://bugs.swift.org/browse/SR-6192 .

A workaround for this type logic seems to be

type(of: obj) == [SomeType].self

To expand on the example above,

var obj = [Int]()

obj is [String] // true
type(of: obj) == [String].self // false
type(of: obj) == [Int].self // true

obj.append(3)

obj is [String] // false
type(of: obj) == [String].self // false