What is the preferred way to check if an optional has a value without using it?

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?


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.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *