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? Unfortunately, it is not working in Swift3 anymore. What would be the "new" way to achieve this?
The syntax does not work in Swift 2 either.
First of all let's use a Swift compliant name
struct MyStruct { ... }
You have two options:
myVariable : MyStruct?
declares an optional struct without a value (nil
)
myVariable : MyStruct? = MyStruct()
declares an optional empty struct.
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. Swift encourages you to use non-optional types a much as possible.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments