casting - Tuple "upcasting" in Swift -


if have tuple signature (string, bool) cannot cast (string, any). compiler says:

error: cannot express tuple conversion '(string, bool)' '(string, any)'

but should work since bool can casted safely any as. same error gets thrown if that:

let any: = ("string", true) as! (string, any) // error as! (string, bool) // succeeds 

error:

could not cast value of type '(swift.string, swift.bool)' '(protocol<>, protocol<>)'

so there workaround second scenario? because cannot cast any tuple (any, any) cast elements separately.

tuples cannot cast, if types contain can. example:

let nums = (1, 5, 9) let doublenums = nums (double, double, double) //fails 

but:

let nums : (double, double, double) = (1, 5, 9) //succeeds 

the workaround in case cast individual element, not tuple itself:

let tuple = ("string", true) let anytuple = (tuple.0, tuple.1 any) // anytuple (string, any) 

this 1 of reasons the swift documentation notes:

tuples useful temporary groups of related values. not suited creation of complex data structures. if data structure persist beyond temporary scope, model class or structure, rather tuple.

i think implementation limitation because tuples compound types functions. similarly, cannot create extensions of tuples (e.g. extension (string, bool) { … }).


if you're working api returns (string, any), try change use class or struct. if you're powerless improve api, can switch on second element's type:

let tuple : (string, any) = ("string", true)  switch tuple.1 {  case let x bool:     print("it's bool")     let booltuple = (tuple.0, tuple.1 as! bool)  case let x double:     print("it's double")     let doubletuple = (tuple.0, tuple.1 as! double)  case let x nsdateformatter:     print("it's nsdateformatter")     let dateformattertuple = (tuple.0, tuple.1 as! nsdateformatter)  default:     print("unsupported type") } 

if api returns any , tuple isn't guaranteed (string, any), you're out of luck.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -