2

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
  • Use your first example if you need more Swift-y, future-proofing and the name placeholder. Use your second example if reading more naturally and reflexivity is more important to you. Commented Sep 23, 2016 at 20:08

1 Answer 1

1

I don't think there's anything particularly Swifty about the first method.

I would go with the second approach.

  1. I think the second one is more understandable, especially for new language learners, for whom the if let syntax is foreign.
  2. The second approach can be negated. if x != nil can become if x == nil with a single character change, but there's nothing similar in the if let _ = x case.
1
  • Those are both great points!
    – Ky -
    Commented Apr 30, 2017 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.