sebspi
sebspi

Reputation: 41

Change protocol return type for method

I have a little problem with my Protocol "Model" and a Class "Device" that conforms to "Model." In my Protocol I have a function which has a return value "Model". In my class, I have this implementation function and want to change the return type from "Model" to "Device". But if I change this, i have to add the original function again.

My Model protocol:

protocol Model {
    func fromJSON(jsonString : String) -> Model
}

My Device Class:

class Device : Model {
    func fromJSON(jsonString: String) -> Model {
        var jsonObj = JSON(jsonString)
        var device = Device()
        return device
    }
}

When I try to assign the result of this function to a Device variable, I get this error-message:

Cannot assign a value of type "Model" to a value of type "Device"

let jsonString: String = "MY ARRAY";
var device2 = Device()
device2 = Device().fromJSON(jsonString)

Upvotes: 2

Views: 2075

Answers (1)

Rob Napier
Rob Napier

Reputation: 299265

Your Model protocol makes a promise:

func fromJSON(jsonString : String) -> Model

It promises to return some Model. It doesn't promise to return the same kind of Model as the implementer. If you mean that, it's called Self.

protocol Model {
    func fromJSON(jsonString : String) -> Self
}

With classes, this is a bit of a pain to implement. Ideally your Device should be a struct, which makes it trivial. But if you mark the class final, then it's fine as well:

protocol Model {
    static func fromJSON(jsonString : String) -> Self
}

final class Device : Model {
    class func fromJSON(jsonString: String) -> Device {
        let device = Device()
        return device
    }
}

But really, this whole protocol makes no sense. What you really want is a initializer:

protocol Model {
    init(jsonString : String)
}

class Device : Model {
    required init(jsonString: String) {
        ...
    }
}

Upvotes: 3

Related Questions