加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

斯威夫特中的元组“向上倾斜”

发布时间:2020-12-14 05:44:00 所属栏目:百科 来源:网络整理
导读:如果我有一个带签名的元组(String,Bool),我无法将其转换为(String,Any).编译器说: error: cannot express tuple conversion ‘(String,Bool)’ to ‘(String, Any)’ 但这应该可行,因为Bool可以安全地转换为Any with as.如果您执行类似的操作,几乎会抛出相
如果我有一个带签名的元组(String,Bool),我无法将其转换为(String,Any).编译器说:

error: cannot express tuple conversion ‘(String,Bool)’ to ‘(String,
Any)’

但这应该可行,因为Bool可以安全地转换为Any with as.如果您执行类似的操作,几乎会抛出相同的错误:

let any: Any = ("String",true)
any as! (String,Any) // error
any as! (String,Bool) // obviously succeeds

错误:

Could not cast value of type ‘(Swift.String,Swift.Bool)’ to
‘(protocol<>,protocol<>)’

那么有没有针对第二种情况的解决方法?因为您甚至无法将Any转换为任何可以单独转换元素的元组(Any,Any).

即使它们包含的类型可以,也无法强制转换元组.例如:
let nums = (1,5,9)
let doubleNums = nums as (Double,Double,Double) //fails

但:

let nums : (Double,Double) = (1,9) //succeeds

在你的情况下,解决方法是强制转换单个元素,而不是元组本身:

let tuple = ("String",true)
let anyTuple = (tuple.0,tuple.1 as Any)
// anyTuple is (String,Any)

这是the Swift documentation注意到的原因之一:

Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope,model it as a class or structure,rather than as a tuple.

我认为这是一个实现限制,因为元组是像函数一样的复合类型.同样,你不能创建元组的扩展(例如扩展(String,Bool){…}).

如果您实际使用的是返回(String,Any)的API,请尝试将其更改为使用类或结构.但是如果你无力改进API,你可以打开第二个元素的类型:

let tuple : (String,Any) = ("string",true)

switch tuple.1 {

case let x as Bool:
    print("It's a Bool")
    let boolTuple = (tuple.0,tuple.1 as! Bool)

case let x as Double:
    print("It's a Double")
    let doubleTuple = (tuple.0,tuple.1 as! Double)

case let x as NSDateFormatter:
    print("It's an NSDateFormatter")
    let dateFormatterTuple = (tuple.0,tuple.1 as! NSDateFormatter)

default:
    print("Unsupported type")
}

如果API返回Any并且不保证元组(String,Any),那么你运气不好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读