Dribbler
Dribbler

Reputation: 4681

Is it possible to use optionals for members in structures or classes in Swift?

I'm having a difficulty reconciling my admittedly incomplete understanding of optionals and this from the Swift 2.1 documentation:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

I'd like to be able to do something like:

struct Name {
    var firstName = "Flintstone First"
    var middleName: String?
    var lastName = "Flintstone"
}

var wilmaHusband: Name
wilmaHusband.firstName = "Fred"

where middleName may be nil. However, quite understandably according to that part of the Swift documentation, I encounter the error Struct wilmaHusband must be completely initialized before a member is stored...

Is what I'm trying to do--make a member potentially nil in a structure (or class) impossible in Swift? If so, it seems one seeming advantage of optionals--that they may hold the kind of data that may or may not be present in a structured object (such as a middle name in a name construct)--is lost.

I feel like I'm missing something fundamental here in my understanding of optionals, and I apologize in advance for my naïveté.

Upvotes: 0

Views: 111

Answers (1)

Martin R
Martin R

Reputation: 539685

Since all members of the struct have an initial value (including var middleName: String? which – as an optional – is implicitly initialized to nil), you can create a variable of that type simply with

var wilmaHusband = Name()

Upvotes: 2

Related Questions