swift - How to check if Optional is not nil and property is true in one expression? -
using swift, have nsstatusitem, , when click it, want check if nswindow visible. if is, hide it, if isn't, call function show nswindow.
my nswindow class property in app delegate, var window: nswindow?. in method responds clicking of nsstatusitem, trying use optional chaining following:
if self.window?.visible { self.window!.orderout(self) // or self.window?.orderout(self), same behavior } else { displaywindow() } however, if window not nil, goes if block every time. if window is nil, goes else block every time. in other words, doesn't appear work. cannot check if window not nil , if window visible in 1 expression. (i figured obvious place use optional chaining.)
i tried this, see happen:
if self.window!.visible { self.window!.orderout(self) } else { displaywindow() } which works if window not nil. window hidden @ first, hits else block , shows window. next time method called, window visible, else block. , on. want, except cannot check if window nil. if nil, obvious crash "fatal error: can't unwrap optional.none"
the following allows me check if window nil, , check if visible:
if let win = self.window { if win.visible { win.orderout(self) } else { displaywindow() } } else { nslog("self.window == nil") } however, wordy , think should able first way. have third way? or correct in assuming first case not working bug?
edit: way works:
if self.window && self.window!.visible { self.window?.orderout(self) } else { displaywindow() } but again, isn't optional chaining meant replace kind of thing?
edit:
cezar's solution (first comment below) turned out more correct:
self.window?.visible == true there serious flaw solution below. if self.window nil, try unwrap nil , crash.
--old answer--
as mentioned in comment:
when use optional chaining, returned value optional. means self.window?.visible returns bool?. , since exists when window not nil, pass check.
this explained in swift book section on optional chaining. makes sense because when use optional chaining, return value has chance return nil, , doesn't depend on final value in "chain".
note: above still true, following suggestion terrible :[
desired syntax is:
(self.window?.visible)! here's code paste playground play behavior:
import foundation class { let t = true; let f = false; } class b { var a:a? } let b = b() b.a = a() if b.a?.f == true { println("true") } else { println("false") // prints false }
Comments
Post a Comment