ios - Using if statements in Swift? -
whats best way execute code if optional isn't nil? clearly, obvious way directly check if value nil:
if optionalvalue != nil { //execute code }
i've seen following:
if let _ = optionalvalue { //execute code }
the second 1 seems more in line swift since it's using optional chaining. there advantages using 1 method on other? there better way it? better mean "more in line swift", whatever means.
optional binding should used if need unwrapped value. shortcut longer expression, , think should thought in terms. in fact, in swift 1.2 optional binding expression:
if let unwrapped = optional { println("use unwrapped value \(unwrapped)") }
is syntactic sugar code (remember optionals are, under hood, instances of optional<t>
enumeration):
switch optional { case .some(let unwrapped): println("use unwrapped value \(unwrapped)") case .none: break }
using optional binding , not assigning unwrapped value variable having box may contain tv inside. don't remove tv box if purpose verify whether box empty or not - open box , inside.
so, if need execute code if variable not nil, don't need nor use actual value contained in optional variable, not-nil check is, in opinion, best way it.
Comments
Post a Comment