空数组可以转换为任何类型的数组 [英] Empty array can be cast to array of any type

查看:105
本文介绍了空数组可以转换为任何类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Swift中的空数组可以强制转换为任何数组类型.

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

请参见以下示例:

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?

推荐答案

正如@Hamish指出的,这确实是一个已知问题.他的评论指向错误报告 https://bugs.swift.org/browse/SR-6192.

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

这篇关于空数组可以转换为任何类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆