delegating initializers in structs are not marked with 'convenience'

Viewed 9338

I keep getting this error and I don't understand why.

error: delegating initializers in structs are not marked with 'convenience'

This is what I have (as an example), a DeprecatedCurrency and a SupportedCurrency.

struct DeprecatedCurrency {
    let code: String
}

struct SupportedCurrency {
    let code: String
}

I then want to add a convenience init function for converting from the deprecated currency object to the new currency object. And this is what I have:

struct DeprecatedCurrency {
    let code: String
}

struct SupportedCurrency {
    let code: String

    convenience init(_ currecny: DeprecatedCurrency) { // error!!
        self.init(code: currecny.code)
    }

    init(code: String) {
        self.code = code
    }
}

What does this error even mean and how do I fix it?


I know that if we don't provide a default initializer, a initializer with signature init(code: String) will be automatically generated for us with struct in Swift. So by the end of the day, what I am really looking for is (if possible):

struct SupportedCurrency {
    let code: String

    convenience init(_ currecny: DeprecatedCurrency) { // error!!
        self.init(code: currecny.code)
    }
}
3 Answers

One option is to add the new init in an extension of your struct. This way, you wont loose the default auto generated memberwise initialiser.

struct SupportedCurrency {
    let code: String

}

extension SupportedCurrency {
   init(_ currency: DeprecatedCurrency) {
        self.init(code: currency.code)
    }
}

From Apple docs

NOTE

If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type’s original implementation. For more information, see Extensions.

Related