Reputation: 435
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. )
Upvotes: 0
Views: 88
Reputation: 187
Please find piece of code below. If you want to use it as let constant.
let action: Action {
get {
switch self.defaultView {
case fromView:
return Action.push
case toView:
return Action.pop
default:
return Action.swap
}
}
}
Upvotes: 0
Reputation: 59526
This is the right syntax for populating a constant using your conditions
let action = { () -> Action in
switch self.defaultView {
case self.fromView: return .push
case self.toView: return .pop
default: return .swap
}
}()
Full example
import UIKit
class ViewController: UIViewController {
let fromView = UIView()
let defaultView = UIView()
let toView = UIView()
func foo() {
let action = { () -> Action in
switch self.defaultView {
case self.fromView: return .push
case self.toView: return .pop
default: return .swap
}
}()
}
}
enum Action {
case push, pop, swap
}
Upvotes: 0
Reputation: 5563
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.
Upvotes: 2