swift Tips

  1. 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
修正下 這個(gè)目前在swift4.2中已經(jīng)無(wú)法使用了

image.png

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)
正確使用方式

  1. func 參數(shù)修飾

// func 的參數(shù)修飾
// func incrementor(variable: Int) -> Int {
// return 10
// }
// 等價(jià)于
// func letincrementor(let variable: Int) -> Int {
// return 10
// }
// 編譯錯(cuò)誤
// func letincrementor(let variable: Int) -> Int {
// return variable++
// }
// 如何做到 variable++
// func letincrementor(var variable: Int) -> Int {
// return variable++
// }
// 雖然支持 ++ 但是外部變量是沒(méi)有被修改
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)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容