Wednesday, 15 August 2012

swift - How to properly check if non-Optional return value is valid? -



swift - How to properly check if non-Optional return value is valid? -

i've run odd case when trying check homecoming value, , i'm wondering how "properly", in swift sense.

i have nsstatusitem (named item), , i'm trying assign nsstatusitem nsimage. when create nsimage, since pass string value image name, want create sure nsimage valid (what if mistype image name string?).

the first thing tried this:

if allow image: nsimage? = nsimage(named: "correcticonname") { item.image = image }

but gives error "bound value in conditional binding must of optional type". thought saying image: nsimage? made clear optional, guess not.

i changed this:

let image: nsimage? = nsimage(named: "correcticonname") if image { item.image = image }

which works totally fine. don't why works, while first illustration doesn't. seems more-or-less exact same thing. , since first 1 didn't compile, thought i'd seek other routes...

since nsimage(named:) homecoming nsimage , not nsimage?, thought i'd see happened if assigned homecoming value of constructor straight item:

item.image = nsimage(named: "correcticonname")

which works, doesn't allow error checking want do. if string wrong, nsstatusitem gets nil image, leads me having invisible status bar item.

next, tried this:

let image: nsimage = nsimage(named: "correcticonname") if image { item.image = image }

but gives error "type 'nsimage' not confirm protocol 'logicvalue'", guess means aren't allowed check if it's nil or not if statement.

however, can check whether nil doing following:

let image: nsimage = nsimage(named: "correcticonname") if image != nil { item.image = image }

so, here's question: how 1 supposed check homecoming value if isn't optional?

it is optional, compiler isn't showing you.

in apple's documentation working objective-c objects, says objects imported objective-c apis implicitly unwrapped optionals (like manually declare !):

in cases, might absolutely objective-c method or property never returns nil object reference. create objects in special scenario more convenient work with, swift imports object types implicitly unwrapped optionals. implicitly unwrapped optional types include of safety features of optional types. in addition, can access value straight without checking nil or unwrapping yourself. [source]

unfortunately, compiler/syntax checker doesn't treat them such. therefore, right way of checking declare image type nsimage initializer returning, implicitly unwrapped optional nsimage:

let image: nsimage! = nsimage(named: "correcticonname") if image { // }

alternate method (via @vacawama):

if allow image = nsimage(named: "correcticonname") nsimage! { // }

swift

No comments:

Post a Comment