Optionals

Finally, no discussion of generics would be complete without mentioning optionals. Optionals are implemented as enumerations, but they’re also just another generic type, which you could have defined yourself.

Suppose you were writing an app that let a user enter her birthdate in a form, but didn’t require it. You might find it handy to define an enum type, as follows:

enum OptionalDate { case none

case some(Date)

}

Similarly, if another form allowed but didn’t require the user to enter her last name, you might define the following type:

enum OptionalString { case none

case some(String)

}

Then you could capture all the information a user did or did not enter into a struct with properties of those types:

struct FormResults {

// other properties here var birthday: OptionalDate var lastName: OptionalString

}

And if you found yourself doing this repeatedly for new types of data the user might not provide, then at some point you’d want to generalize this into a generic type that represented the concept of “a value of a certain type that might be present”, and you’d write the following:

enum Optional<Wrapped> { case none

case some(Wrapped)

}

At this point, you would have reproduced Swift’s own Optional<Wrapped> type, since this is quite close to the definition in the Swift standard library! It turns out, Optional<Wrapped> is close to being a plain old generic type, like one you could write yourself.

Why “close”? It would only be a plain old generic type if you interacted with optionals only by writing out their full types, like so:

var birthdate: Optional<Date> = .none if birthdate == .none {

// no birthdate

}

But, of course, it’s more common and conventional to write something like this:

var birthdate: Date? = nil if birthdate == nil {

// no birthdate

}

In fact, those two code blocks say exactly the same thing. The second relies on special language support for generics: the Wrapped? shorthand syntax for specifying the optional type Optional<Wrapped>, and nil, which can stand for the .none value of an Optional<Wrapped> specialized on any type.

As with arrays and dictionaries, optionals get a privileged place in the language with this syntax to make using them more concise. But all of these features provide more convenient ways to access the underlying type, which is simply a generic type.

results matching ""

    No results matching ""