swift - 结构成员初始化 - 省略具有默认值的属性的值

标签 swift

我是 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/

相关文章:

ios - 将 PDF 图像添加到 UIBarItem Swift

ios - 如何制作带有居中注释的可拖动 map

ios - UITextField - textFieldDidEndEditing 调用太迟

iOS - Parse.com 导出数据自动化

ios - 加载 TableView 时项目出错

ios - 当 textFieldDidBeginEditing 中的 tableView.reloadData() 时键盘不显示

ios - Swift 编译器问题 : Compiler doesn't compile long parameters array for Alamofire post request

ios - Swift 单元测试中的类型名称不明确

ios - 使用不同的模态样式呈现和关闭

swift - 如何在 Xcode 10.1 中渲染 DAE (COLLADA) 文件。目前正在崩溃