Swift - use of optional with let

A constant that's an optional needs to be assigned a value during the init process. That value can be nil, or some other value. Once assigned it is stuck in that value. A nil is like a "this property intentionally left blank" indicator, written in permanent ink.

Say you have a class that gets filled with response data from a network request. Some of the fields you get back may be nil, or they may contain data.

You write code that parses the response from the server and builds a response object. Each property of the response object is fixed. It either contains data if you got information for that property, or nil.

In that case it makes perfect sense to use an optional constant.

You'd write an init method for your response object that would take the network reply (In JSON, for example) and fill out the properties of the response object. If a given tag in the JSON data is missing, you'd set that property to nil. You use a constant because the value is fixed once the response object is initialized. If it's nil, it will be nil forever. If it contains a value, it will always contain that value and it can't be changed.


Only optional variable will be automatically set to nil if no initial value provided


Optional constant of type T? will NOT be automatically set to nil
it needs to be manually initialised with a value of type T or nil

  • If it is not manually initialised before used, an error "constant used before being initialised" will be thrown

  • Similarly, if a class has an optional constant property without explicitly, manually initialising it and also has no construct, an error "class has no initialisers" will be thrown


If you're putting a literal and you make it optional, the optional part is useless because you know that number is going to be 1

let number: Int? = 1

However, if you want to make a constant copy of another object, where you don't know if the source is going to be nil or not, it is.

var array = ["hello"]
let string: String? = array[1]

// string is nil, so you can do some checking with it

The above example does not quite illustrate my point, but assume that array is a mutable array which you might be removing and adding values sporadically (where you may get a nil value if you're checking for the "1" index)