swift - Swift 中的元组 "upcasting"

标签 swift casting tuples swift2

如果我有一个带有签名(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/

相关文章:

c++ - 将 int 转换为 size_t

java - Java中的隐式对象类型?

python 入口小部件元组组合

swift - Swift 中的元组与结构

ios - WKWebView 和 NSURLProtocol 不工作

swift - 如何向 CloudKit 中的现有记录添加字段

ios - swift 中嵌套字典 API 的结构

swift - 如何在 swift 中访问像 $(PROJECT_DIR) 这样的build设置常量?

java - 找到元素并打印大量的一部分

python - 这段代码如何从整数字符串中提取最大值和最小值?