PM Extra PM Extra - 1 year ago 53
Swift Question

Swift 3: How to let a constant according to different case?

let action = { () -> Action in
if fromView == self.defaultView {
return Action.push
} else if toView == self.defaultView {
return Action.pop
} else {
return Action.swap

I want to let a constant according to different case.

Is this the right way?
(It's works fine, I just want to find a more elegant way. )

Answer Source

If you're doing this inside a method (and your action variable is not a property), you don't need the closure, you can write :

let action: Action
if fromView == self.defaultView {
    action = .push
} else if toView == self.defaultView {
    action = .pop
} else {
    action = .swap

If your if/else handles all the cases, the compiler will not complain that the action variable is used uninitialized.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download