简体   繁体   English

空数组可以强制转换为任何类型的数组

[英]Empty array can be cast to array of any type

It seems empty arrays in Swift can be cast to any array type. 似乎Swift中的空数组可以强制转换为任何数组类型。

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. 正如@Hamish指出的,这确实是一个已知问题。 His comment points to bug report https://bugs.swift.org/browse/SR-6192 . 他的评论指向错误报告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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM