简体   繁体   中英

Empty array can be cast to array of any type

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?

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

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