Rhythmic Fistman Rhythmic Fistman - 4 months ago 12
Swift Question

typecasting tuples in swift

I'm trying without success to unwrap and cast multiple optionals via tuples. The strange thing is that unwrapping individual items works.
It has been suggested that I'm misusing the downcast

operator,
and that's very likely, but I just can't see it.

Can anyone explain why this doesn't work?

class fooba { }

func unwrapPair(a: AnyObject?, _ b:AnyObject?) {
if let a = a as? fooba {
// true
}

if let b = b as? fooba {
// true
}

if let (a, b) = (a, b) as? (fooba, fooba) {
// false!?!?
}
}
unwrapPair(fooba(), fooba())


I don't think this is a duplicate of tuple "upcasting",
because aren't I downcasting? In any case, explaining exactly how
they're duplicates would be illuminating and an answer in itself.

ank ank
Answer

Instead of separately trying to match each component with if-let combinations, you can just do the same in a more swift-y way:

switch (a, b) {
case (let a as String, _):
    // Do whatever you need to do with a
    return true
case (_, let b as String):
    // Do whatever you need to do with b
    return true
case (let a as NSNumber, let b as NSNumber):
    // Do whatever you need to do with a and b
    return false
default:
    return true
}