- swift curried(柯里化)
func greaterThan(comparor: Int)(input: Int) -> Bool {
return comparor >= input;
}
func demoMethod() -> Bool {
let greaterThan10 = greaterThan(10)
return greaterThan10(13);
}
https://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/?utm_campaign=iOS_Dev_Weekly_Issue_157&utm_medium=email
修正下 这个目前在swift4.2中已经无法使用了
func curriedMethod(a: Int) -> (Int) -> (Int) -> Int{
return {(b: Int) -> (Int) -> Int in
return { (c: Int) -> Int in
return a + b + c
}
}
}
let method10 = curriedMethod(a: 10)
let method1020 = method10(20)
let method102030 = method1020(20)
正确使用方式
- func 参数修饰
// func 的参数修饰
// func incrementor(variable: Int) -> Int {
// return 10
// }
// 等价于
// func letincrementor(let variable: Int) -> Int {
// return 10
// }
// 编译错误
// func letincrementor(let variable: Int) -> Int {
// return variable++
// }
// 如何做到 variable++
// func letincrementor(var variable: Int) -> Int {
// return variable++
// }
// 虽然支持 ++ 但是外部变量是没有被修改
func demo1(addnumber: inout Int) {
addnumber = addnumber + 1
}
func demo2(addnumber: Int) {
print("addnumber:\n(addnumber)")
}
func makeIncrementor(addNumber: Int) -> ((inout Int) -> ()) {
func incrementor ( variable: inout Int) -> () {
variable += addNumber;
}
return incrementor;
}
var number1 = 10
demo1(addnumber: &number1)
demo2(addnumber: 10)
let incrementor10 = makeIncrementor(addNumber: 10)
incrementor10(&number1)
// Present the view controller in the Live View window
print(number1)
网友评论