Which of these is the ideal way to check if a value exists without caring exactly what its value is?
if let _ = flags[.showField] { showField() }
if flags[.showField] != nil { showField() }
In the first case, it seems more Swift-y to use if let _ =
and futureproofs it (I can imagine a future where Apple says you must ask the optional if it has a value instead of comparing to nil
). Additionally, if you come back to modify the code and find you need the value, you can just replace the _
with a name.
In the second case, it reads more naturally and is reflexive with if x == nil
in a way that if let _ =
is not.
Is one of these preferred over the other? If so, which and why?
1
I don’t think there’s anything particularly Swifty about the first method.
I would go with the second approach.
- I think the second one is more understandable, especially for new language learners, for whom the
if let
syntax is foreign. - The second approach can be negated.
if x != nil
can becomeif x == nil
with a single character change, but there’s nothing similar in theif let _ = x
case.
1