Search code examples
swiftcastingswift2anyobject

Problems with associated values of enums


I have created a response enum for my network return value and a function which should return an AnyObject because it becomes it has to be a value of a key.

enum Response {

    case Success(value:AnyObject)
    case Failure(errorNumber: Int)

    func getResponse() -> AnyObject{
        switch self {
        case .Success(value: AnyObject):
            return value
        case .Failure(errorNumber: Int):
            return errorNumber
        }
    }

}

Generating the errors below: enter image description here I didn't add the actual text for the errors because I wanted to show you that it even doesn't do syntax highlighting for errorNumber and value

Eventually in my code I would have to assign this value to an AnyObject which later that anyobject will be downcasted to [NSObject : AnyObject]

So I would have:

var data : AnyObject? // <-- from our internal framework
data = Response.Success(data)
var params = data as! [NSObject : AnyObject] // <-- from our internal framework

The first code snippet is my new code, but the internal frameworks are lines of code I can't change.

FYI Our code is still using Swift2 :(


Solution

  • I'd suggest you give the Swift Book a read:

    func getResponse() -> Any {
        switch self {
        case .Success(let value):
            return value
        case .Failure(let errorNumber):
            return errorNumber
        }
    }