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

斯威夫特中的元组“向上倾斜”,第1张

概述如果我有一个带签名的元组(String,Bool),我无法将其转换为(String,Any).编译器说: error: cannot express tuple conversion ‘(String, Bool)’ to ‘(String, Any)’ 但这应该可行,因为Bool可以安全地转换为Any with as.如果您执行类似的 *** 作,几乎会抛出相同的错误: let any: Any = ( 如果我有一个带签名的元组(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) // errorany 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),那么你运气不好.

总结

以上是内存溢出为你收集整理的斯威夫特中的元组“向上倾斜”全部内容,希望文章能够帮你解决斯威夫特中的元组“向上倾斜”所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1047943.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存