Optional struct in Swift3

beginneR

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?

vadian

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Swift 3 Equatable Struct optional function

From Dev

Swift Initialize Struct with optional stored properties

From Dev

Swift3 : unexpectedly found nil while unwrapping an Optional value

From Dev

Different process between Struct and Class in mutating asynchronously in Swift3

From Dev

How to init a struct var with Data in swift3

From Dev

Optional struct field

From Dev

Swift Optional of Optional

From Dev

Swift 3 optional unwrapping

From Dev

Swift 3 optional parameters

From Dev

Why do I need to declare an optional value as nil explicitly in Struct - Swift

From Dev

Swift 3: How to read from "Optional(Optional(stringValue))" without optional?

From Dev

Swift: Optional Text In Optional Value

From Dev

Optional let and optional var inside a class in Swift

From Dev

Swift Array optional Type and subscripting (Beta 3)

From Dev

Swift 3: 'if let' optional binding error

From Dev

Swift 3 - ! vs ? for optional function parameters

From Dev

Swift 3: Meaning of parenthesis around unwrapped optional

From Dev

Correct way to unwrap an Optional Integer in Swift 3

From Dev

Struct inside subclass, unwrap optional when assigning to self

From Dev

Wrap a function that takes a struct of optional arguments using kwargs

From Java

What is an optional value in Swift?

From Dev

Swift Lazy and Optional properties

From Dev

Optional binding syntax in Swift

From Dev

Optional dynamic properties in Swift

From Dev

Swift tuple to Optional assignment

From Dev

Calling an optional function in Swift

From Dev

optional closure property in Swift

From Dev

Map with Optional Unwrapping in Swift

From Dev

Swift: optional array count

Related Related

HotTag

Archive