Search code examples
swifttype-erasureinitializeranyobject

Is it correct to say all erased types are non-initializable?


(By erased types I mean: (Any, AnyHashable, AnyObject), protocol, or root class NSObject).

I'm asking this question because in the code below I can't initialize something to AnyObject. I get error:

cannot invoke initializer for type 'AnyObject?' with no arguments

and I'm looking for a proper workAround. I don't think the right choice is to initialize something in each statement...

func returnObject() -> AnyObject{

    var something = AnyObject()

    if x == someProperty{
        something = y
    }
    else if x == anotherProperty{
        something = z
    }else{
        something = t
    }
    return something   

}

Solution

  • What would you expect the initialization to do? What does it matter anyway, if you plan to immediately overwrite something with y, z or t?

    func returnObject() -> AnyObject {
    
        let something: AnyObject
    
        if x == someProperty{
            something = y
        }
        else if x == anotherProperty{
            something = z
        }
        else{
            something = t
        }
        return something   
    
    }
    

    However, it's more succinct to use a switch:

    func returnObject() -> AnyObject {
        let something: AnyObject
    
        switch x {
            case someProperty:    something = y
            case anotherProperty: something = z
            default:              something = t
        }
    
        return something
    }
    

    And if you're just returning something, you can just inline it:

    func returnObject() -> AnyObject {
        switch x {
            case someProperty:    return y
            case anotherProperty: return z
            default:              return t
        }
    }