swiftunwrap

Unwrapping either one of two types in Swift


I have a method which does exactly the same thing for two types of data in Swift.

To keep things simple (and without duplicating a method) I pass AnyObject as an argument to my method which can be either of these two types. How to I unwrap it with an || (OR) statement so I can proceed? Or maybe this done otherwise?

func myFunc(data:AnyObject) {

    if let data = data as? TypeOne {
        // This works fine. But I need it to look something like unwrapping below
    }

    if let data = data as? TypeOne || let data = data as? TypeTwo { // <-- I need something like this
        // Do my stuff here, but this doesn't work
    }

}

I'm sure this is trivial in Swift, I just can't figure out how to make it work.


Solution

  • You can't unify two different casts of the same thing. You have to keep them separate because they are two different casts to two different types which the compiler needs to treat in two different ways.

    var x = "howdy" as AnyObject
    // x = 1 as AnyObject
    
    // so x could have an underlying String or Int
    switch x {
    case let x as String:
        print(x)
    case let x as Int:
        print(x)
    default: break
    }
    

    You can call the same method from within those two different cases, if you have a way of passing a String or an Int to it; but that's the best you can do.

    func printAnything(what:Any) {
        print(what)
    }
    switch x {
    case let x as String:
        printAnything(x)
    case let x as Int:
        printAnything(x)
    default: break
    }
    

    Of course you can ask

    if (x is String || x is Int) {
    

    but the problem is that you are no closer to performing an actual cast. The casts will still have to be performed separately.