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

前端之家收集整理的这篇文章主要介绍了斯威夫特中的元组“向上倾斜”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个带签名的元组(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) // obv@R_502_437@sly 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),那么你运气不好.

原文链接:/swift/319953.html

猜你在找的Swift相关文章