gpt4 book ai didi

swift - Swift 中的元组 "upcasting"

转载 作者:IT王子 更新时间:2023-10-29 05:43:56 24 4
gpt4 key购买 nike

如果我有一个带有签名(String, Bool) 的元组,我不能将它转换为(String, Any)。编译器说:

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

但这应该有效,因为可以使用 asBool 安全地转换为 Any。如果你这样做,几乎会抛出同样的错误:

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, Double) = (1, 5, 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.

我认为这是一个实现限制,因为元组是类似于函数的复合类型。同样,您不能创建元组的扩展(例如 extension (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 - Swift 中的元组 "upcasting",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31270507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com