Fast optional peg with negative result

How can I do optional binding in Swift and test for a negative result? Let's say, for example, I have an additional view controller that I would like to be lazy. When it's time to use it, I would like to check if it's not there and initialize it if it's not done yet.

I can do something like this:

if let vc = viewController? {
   // do something with it
} else {
   // initialize it
   // do something with it
}

      

But this is kludgey and inefficient, and requires me to type in the "do something with it" code twice or bury it in a closure. An obvious way to improve this from objC's experience would be something like this:

if !(let vc = viewController?) {
   // initialize it
}
if let vc = viewController? {
   // do something with it
}

      

But it binds you to a "template binding error cannot appear in expression" which tells me not to put the binding in the parenthesis and try to evaluate it as an expression, which is of course exactly what trying to do ...

Or another way to write what actually works:

if let vc = viewController? {

} else {
   // initialize it
}
if let vc = viewController? {
   // do something with it
}

      

But this is ... stupid ... for lack of a better word. There must be a better way!

How can I make an optional binding and check for a negative default? Surely this is a common use case?

+3


source to share


2 answers


you can implicitly use Optional

for boolean

if !viewController {
    viewController = // something
}

let vc = viewController! // you know it must be non-nil 
vc.doSomething()

      




Update: In Xcode6-beta5, Optional

no longer correspond to the LogicValue

/ BooleanType

, you need to check it with the nil

using ==

or!=

if viewController == nil {
    viewController = // something
}

      

+4


source


Will this work for you?



if viewController == nil {
  // initialize it
}

// do something with it

      

+2


source







All Articles