Difference between revisions of "W1035 Not a Value"
(→Nil) |
|||
Line 10: | Line 10: | ||
== Nil == | == Nil == | ||
Nil represents the absence of value ''of the specified type''. We indicate that we | Nil represents the absence of value ''of the specified type''. We indicate that we intend to accept such '''nil''' values by specifying the type explicitly and suffixing the type name with a question mark. For example, in the aforementioned case, rather than specify the type as: | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
let middleName : Character | let middleName : Character | ||
Line 17: | Line 17: | ||
<syntaxhighlight lang="swift"> | <syntaxhighlight lang="swift"> | ||
let middleName : Character? | let middleName : Character? | ||
</syntaxhighlight> | |||
This enables us to specify ''either'' a character ''or'' the special place-holder for ''no value'', '''nil''': | |||
<syntaxhighlight lang="swift"> | |||
let middleName : Character? = "A" | |||
</syntaxhighlight> | |||
-or- | |||
<syntaxhighlight lang="swift"> | |||
let middleName : Character? = nil | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 23:07, 7 November 2019
Prerequisites[edit]
Introduction[edit]
There's often a need to represent the absence of a value. For example, consider a database tracking students' first name, middle initial, and last name. Not all students have a middle initial. So what value should we store in a variable representing a student's middle initial if this particular student lacks a middle initial?
The name of this special value, representing non-existence, varies from language to language. In Swift, it's called nil.
Nil[edit]
Nil represents the absence of value of the specified type. We indicate that we intend to accept such nil values by specifying the type explicitly and suffixing the type name with a question mark. For example, in the aforementioned case, rather than specify the type as:
let middleName : Character
we use:
let middleName : Character?
This enables us to specify either a character or the special place-holder for no value, nil:
let middleName : Character? = "A"
-or-
let middleName : Character? = nil