Tuple “upcasting” in Swift

后端 未结 2 950
后悔当初
后悔当初 2020-12-20 15:16

If I have a tuple with signature (String, Bool) I cannot cast it to (String, Any). The compiler says:

error: cannot express

2条回答
  •  既然无缘
    2020-12-20 15:59

    The Swift compiler will enforce that you are explicit about your types. So if you declare it as (String, Bool) it will not allow the conversion.

    The following works as expected in Playground:

    var specificTuple : (String, Bool) = ("Hi", false)
    var generalTuple  : (Any, Any)     = ("Hi", false)
    
    var gany = generalTuple
    gany.1 = "there"
    gany                           // (.0 "Hi", .1 "there")
    
    var spany = specificTuple
    spany.1 = "there"             // error
    

    You can create the (Any, Any) tuple ad hoc but you will need to decompose it

    var any : (Any, Any)  = (specificTuple.0, specificTuple.1)
    any.1 = "there"
    any                          // (.0 "Hi", .1 "there")
    

提交回复
热议问题