Optional types either contain a value or nil. An optional type is defined with a question mark:

var firstLetter: Character?

Optionals can be assigned to either nil or an instance of the optional type. Its initial value will be nil unless you assign a value yourself:

var firstLetter: Character? print(firstLetter) // prints nil firstLetter = “a” print(firstLetter) // prints Optional("a")

Only optional types can be assigned to nil. If you attempt to assign a non-optional type to nil, you will get a compile-time error.

var firstLetter: Character = “a” firstLetter = nil // ERROR: nil' cannot be assigned to type 'Character'



Create a variable called hatColor of type optional String with an initial value of nil.


Reassign hatColor to “blue”.


Reassign hatColor to nil.


Print the value of hatColor. The red text in the console should display some warnings letting us know that there’s more we can do to work with optionals!

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?