After experimenting with currying in Swift, I came up with the code below. I want to see if it's possible to simplify this enum Operate
. Currently, I need to initialize like this:
let multiply = Operate.Multiply.op
I would prefer to have each case have an associated value that directly returns a closure without having to do this hacky switch
block. Is this possible?
Here's some code that you can run in a Swift playground:
import Foundation
enum Operate {
case Plus
case Minus
case Multiply
case unsafeDivide
var op: (Double) -> (Double) -> Double {
get {
switch self {
case .Plus:
return { n in
return { n + $0}
}
case .Minus:
return { n in
return { n - $0}
}
case .Multiply:
return { n in
return { n * $0}
}
case .unsafeDivide:
return { n in
return { n / $0 }
}
}
}
}
}
let multiply = Operate.Multiply.op
let plus = Operate.Plus.op
let unsafeDivide = Operate.unsafeDivide.op
// 3 + (16 * 2) -> 35
plus(3)(multiply(16)(2))
Bonus: How can I handle errors with unsafeDivide
in a 'Swiftly' manner, that is, prevent this:
let unsafeDivide = Operate.unsafeDivide.op
unsafeDivide(2)(0)