natecraft1 natecraft1 - 3 months ago 9
Swift Question

Swift use protocol extension defaults

I have

protocol ErrorContent {
var descriptionLabelText: String { get set }
}
extension ErrorContent {
var descriptionLabelText: String { return "Hi" }
}
struct LoginErrorContent: ErrorContent {
var descriptionLabelText: String
init(error: ApiError) {
...
}
}


and xcode is complaining that "Return from initializer without initializing all stored properties." What I want here is to just use the default value that I gave the descriptionLabelText in the protocol extension. Isn't that the point of protocol extensions? Anyways I'd like to understand why this is wrong and what I can do to use my default value.

Answer

Almost correct, just a couple of issues with your code:

  1. You don't need to declare the variable in LoginErrorContent, as the implementation is already in the ErrorContent extension. Declaring it again overrides the extension implementation

  2. If you want to use the extension computed property for descriptionLabelText, you can't specify that it is a setter, as it only returns a value.

Example:

protocol ErrorContent {
    var descriptionLabelText: String { get }
}

extension ErrorContent {
    var descriptionLabelText: String { return "Hi" }
}

struct LoginErrorContent: ErrorContent {

    // Overriding the extension behaviour
    var descriptionLabelText: String { return "Hello" }

    init(error: ApiError) {
        ...
    }
}
Comments