I’m learning Swift. On first impressions I can't see any point of declaring a constant (without an initial stored value) as an optional within a class
For example:
let userName: String?
because a default initializer would assign it to nil
and it wouldn't subsequently be able to be changed (because it's a constant).
As I understand it, a custom initializer can still assign a non-nil value to it but in that case wouldn't you just declare it as let userName: String
(i.e. non-optional)
I would have expected that if it was a redundant pattern that Apple would have made mention of it but I can't see that they have. So in what situations would an Optional
constant declaration be used or useful?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments