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

如果我有一个带签名的元组(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),那么你运气不好.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...