简体   繁体   English

Swift3中的可选结构

[英]Optional struct in Swift3

I would like to declare a variable that stores an optional struct like so: 我想声明一个存储如下可选结构的变量:

struct my_struct{
    var x: Double
    var y: Double
}

var my_variable = my_struct?

Am I right that this syntax was correct in Swift2? 我对这个语法在Swift2中正确吗? Unfortunately, it is not working in Swift3 anymore. 不幸的是,它不再在Swift3中工作。 What would be the "new" way to achieve this? 实现这一目标的“新”方式是什么?

The syntax does not work in Swift 2 either. 该语法在Swift 2中也不起作用。

First of all let's use a Swift compliant name 首先让我们使用Swift兼容名称

struct MyStruct { ... }

You have two options: 您有两种选择:

  • myVariable : MyStruct? declares an optional struct without a value ( nil ) 声明一个不带值的可选结构( nil

  • myVariable : MyStruct? = MyStruct() myVariable : MyStruct? = MyStruct() declares an optional empty struct. myVariable : MyStruct? = MyStruct()声明一个可选的空结构。

Note: Consider that you have to assign default values for the properties of the struct in the second form or use the memberwise initializer or write a custom initializer. 注意:考虑到您必须以第二种形式为结构的属性分配默认值,或者使用成员初始化器或编写自定义初始化器。

PS: Don't use optionals as a don't-care alibi. PS:不要使用可选内容作为不在乎的不在场证明。 Swift encourages you to use non-optional types a much as possible. Swift鼓励您尽可能使用非可选类型。

struct my_struct{
    var x: Double
    var y: Double
}

var my_variable:my_struct?

Note that types are usually capitalized and camel-cased by convention in Swift eg 请注意,通常在Swift中按约定将类型大写并用驼峰式表示,例如

struct MyStruct {
    var x: Double
    var y: Double
}

var myVariable: MyStruct?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM