委托结构中的初始化程序没有标记为"方便"

Yuc*_*ong 12 swift

我一直收到这个错误,我不明白为什么.

错误:在结构中委派初始化程序没有标记为"方便"

这就是我所拥有的(作为例子),a DeprecatedCurrency和a SupportedCurrency.

struct DeprecatedCurrency {
    let code: String
}

struct SupportedCurrency {
    let code: String
}
Run Code Online (Sandbox Code Playgroud)

然后,我想添加一个便利初始化函数,用于从已弃用的货币对象转换为新的货币对象.这就是我所拥有的:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这个错误甚至意味着什么,我该如何解决?


我知道如果我们不提供默认初始化程序,init(code: String)将使用Swift中的struct自动为我们生成带签名的初始化程序.所以到了最后,我真正想要的是(如果可能的话):

struct SupportedCurrency {
    let code: String

    convenience init(_ currecny: DeprecatedCurrency) { // error!!
        self.init(code: currecny.code)
    }
}
Run Code Online (Sandbox Code Playgroud)

Rah*_*hul 18

只需删除它convenience,它不是必需的struct.

Swift文档.

初始化程序可以调用其他初始化程序来执行实例初始化的一部分.此过程称为初始化程序委派,可避免跨多个初始化程序复制代码.

他们没有提到使用convenience.它是convenience语义的,但不需要关键字.

struct DeprecatedCurrency {
    let code: String
}

struct SupportedCurrency {
    let code: String

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

    init(code: String) {
        self.code = code
    }
}
Run Code Online (Sandbox Code Playgroud)


Jer*_*myP 9

结构不需要这个词 convenience

试试这个:

struct SupportedCurrency {
    let code: String

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

    init(code: String) {
        self.code = code
    }
}
Run Code Online (Sandbox Code Playgroud)

问题不在于我们为什么不把convenience对于结构,但为什么我们把convenience上课.原因是类具有继承性.对于一个类,你需要调用超类的指定构造函数(不确定这是否是正确的术语,它来自Objective-C的初始化器.该单词convenience将构造函数标记为"不是指定的构造函数".

  • 该问题还询问了错误的含义。最初,你没有回答这个问题。既然您已经得到了实际答案,我就删除了不赞成票。 (2认同)
  • 因此,您可以说的最糟糕的情况是,即使问题的答案很容易通过说“结构不需要`方便`”来推断,它也不完整,因为这就是正在发生的事情。当结构不需要方便时,他会使用“方便”。无论如何,感谢您提供反馈(并删除反对票)。许多人不会打扰——尤其是在受到挑战之后。 (2认同)