作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在关于初始化器的 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/
我是一名优秀的程序员,十分优秀!