我是 Swift 的新手,正在关注在线文档。具体来说,我正在查看初始化 ( https://docs.swift.org/swift-book/LanguageGuide/Initialization.html)。
在子标题“结构类型的成员初始化器”下,它说:
When you call a memberwise initializer, you can omit values for any properties that have default values. In the example above, the Size structure has a default value for both its height and width properties. You can omit either property or both properties, and the initializer uses the default value for anything you omit
然后举个例子:
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
let zeroByTwo = Size(height: 2.0)
print(zeroByTwo.width, zeroByTwo.height)
// Prints "0.0 2.0"
let zeroByZero = Size()
print(zeroByZero.width, zeroByZero.height)
// Prints "0.0 0.0"
但是,如果我尝试这样做,我会收到 zeroByTwo
初始化错误:
Cannot invoke initializer for type 'Size' with an argument list of type '(height: Double)'
我是不是误会了什么?
我正在使用 Swift 5。
最佳答案
您引用了 Swift 5.1 version of the Swift Programming Language guide . Swift 5 指南缺少整段内容,因为该功能是 5.1 的新增功能。
在 Swift 5 中,成员初始化器包括所有存储的属性而不考虑默认变量值,因此您在创建新实例时必须包含每个参数(除非您创建自己的初始化器)。
在 Swift 5.1 中,成员初始化器包含任何默认值,因此您可以在创建实例时选择省略这些参数。您可以在此处阅读有关新功能的更多信息:Synthesize default values for the memberwise initializer .
关于swift - 结构成员初始化 - 省略具有默认值的属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56586158/