gpt4 book ai didi

swift - 这是什么意思 : "You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement"?

转载 作者:行者123 更新时间:2023-11-28 08:06:24 27 4
gpt4 key购买 nike

我在关于初始化器的 Swift 文档中找到了这条注释:

You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer.

什么是“显式”实现?那么什么是“隐式”?

“用继承的初始化程序满足要求” 的确切含义是什么?

你能给我一个代码示例吗?我不必在其中提供所需初始化程序的显式实现?

最佳答案

这是一个带有内联解释的示例:

protocol JSONInitializable { // Use Encoders, but just for example
init(fromJSON: String)
}

class Foo: JSONInitializable {
let x: Int

// "required" is necessary because this init is required for the
// conformance to JSONInitializable
required init(fromJSON json: String) {
//...
x = 123 //some value from the JSON
}
}

class Baz: Foo {
// `init(fromJSON json: String)` can be inherited,
// so it's implicitly defined for Baz, as well as Foo.
}

class Bar: Foo {
// The presence of this uninitialized constant `y` requires an
// a value in the declaration, or an initializer that sets it
let y: Int

// Since we didn't specify a value for `y` in its declaration,
// this initializer must be explicitly specified so as to initialize `y`.
// Doing so blocks the inheritance of `init(fromJSON json: String)` from
// the super class, and requires us to define it ourselves,
// in order to preserve conformance to `JSONInitializable`
required init(fromJSON json: String) {
//...
y = 0
super.init(fromJSON: json)
}
}

关于swift - 这是什么意思 : "You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44975479/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com