If you wish to reduce "leakiness", you can dispatch on the null-ness of the variable; Swift lets you write `if let x = x { /* x is non-optional in here * / }`, which binds a non-optional value inside the braces, and `guard let x = x else { return } /* x is non-optional now * /` which binds a non-optional value after the braces. So as soon as you consume an optional value, you are free to "un-leak" it and extract its value (if it has one) immediately.
For example consider a network response that in a JS app might be passed around as an opaque object. In a language like Swift this is infeasible, you have to transition from the network serialized version to concrete models at the network layer. If you encounter mismatches in the expectation of what is optional you have to handle it here at the edge of the program. This enables massively safer code and makes reasoning about your program much simpler if anything.
As a concerete example say an API response tells you if a user is verified(for some domain specific definition of "verified"), additionally you want to know when they were verified maybe to give them a hint when they need to do it again. You coudl model this as:
{
"verified": false,
"verified_at": null
}
before they have verified and {
"verified": true,
"verified_at": "2020-02-24T15:31:12Z"
}
after they have verified.In Swift this would then be modelled as
struct Users {
let verified: Bool
let verifiedAt: Date?
}
However this introduces an Optional which complicates code that needs to deal with users who are verified or not. Instead you could model the same thing and avoid this issue as: {
"verification_status": {
"status": "unverified"
}
}
for the unverified case and {
"verification_status": {
"status": "verified",
"at": "2020-02-24T15:31:12Z"
}
}
for the verified case. In Swift this can be nicely modelled without any Optionals using an enum enum VerificationStatus {
case unverified
case verified(Date)
}
struct User {
let verificationStatus: VerificationStatus
}
Better optional value visibility leads to better data modelling.
/s slightly, maybe more snarky, but seriously, optional types are way overhyped. Null objects are far more useful than optionals. Optionals tend to leak all over the show.