Swift-函数的理解
生活随笔
收集整理的這篇文章主要介紹了
Swift-函数的理解
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/* 函數(shù)(Function) 函數(shù)是為執(zhí)行特定功能的自包含的代碼塊。函數(shù)需要給定一個特定標(biāo)識符(名字),然后當(dāng)需要的時候, 就調(diào)用此函數(shù)來執(zhí)行功能。
*/
// 函數(shù)的定義與調(diào)用
// 定義函數(shù)時,使用關(guān)鍵字func,返回值類型通過->指明,如下:
// 函數(shù)名:sayHello,
// 參數(shù)列表中只有一個參數(shù),叫personName,參數(shù)類型是String
// 函數(shù)返回值類型:String
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting
} // 函數(shù)調(diào)用
println(sayHello("Anna")) // prints "Hello, Anna"
println(sayHello("Brian")) // prints "Hello, Brian" // 簡化函數(shù)體
func sayHelloAgain(personName: String) -> String { return "Hello, " + personName + "!"
} println(sayHelloAgain("Anna")) // 函數(shù)可以有多個參數(shù)
/*! * @brief 返回兩個值的差 * @param start Int類型,范圍區(qū)間的起點 * @param end Int類型,范圍區(qū)間的終點 * @return 返回值為Int類型,表示終點-起點的值 */
func halfOpenRangeLength(start: Int, end: Int) -> Int { return end - start
}
println(halfOpenRangeLength(1, 10)) // prints "9" // 無參數(shù)函數(shù)
func sayHelloWorld() -> String { return "Hello, world"
}
println(sayHelloWorld()) // 無返回值的函數(shù),其實這里沒有指定返回值,也會返回一個特殊的值,Void
func sayGoodbye(personName: String) { println("Goodbye, \(personName)!")
}
sayGoodbye("David") // 函數(shù)返回值是可以忽略的
func printAndCount(stringToPrint: String) -> Int { println(stringToPrint) return countElements(stringToPrint) // 計算字符串的長度
} // 不帶返回值
func printWithoutCounting(stringToPrint: String) { printAndCount(stringToPrint)
} printAndCount("Hello,world")
printWithoutCounting("hello, world") /* * @brief 函數(shù)可以返回元組(多個值) * @param string 字符串 * @return (vowels: Int, consonants: Int, others: Int) * vowels:元音, consonants:輔音,others:其它字符 */ func count(string: String) ->(vowels: Int, consonants: Int, others: Int) { var vowels = 0 var consonants = 0 var others = 0 for c in string { switch String(c).lowercaseString { case "a", "o", "e", "i", "u": ++vowels case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": ++consonants default: ++others } } return (vowels, consonants, others) } let total = count("some arbitrary string!") println("\(total.vowels) vowels and \(total.consonants) consonants") // 外部參數(shù)名(External Parameter Names)
// 有時候使用外部參數(shù)名是很有用的,這直到提示的作用,就好像OC語法中的參數(shù)一樣,見名知意
func someFunction(externalParameterName localParameterName: Int) { // do something
} // 看例子:
func join(lhsString: String, rhsString: String, joiner:String) -> String { return lhsString + joiner + rhsString
}
// 這里調(diào)用的時候,沒有外部參數(shù)名
join("hello", "world", ",") // prints "hello,world" // 加上#號后,參數(shù)名與外部名相同,這是快捷方式
func join(#lhsString: String, #rhsString: String, #joiner:String) -> String { return lhsString + joiner + rhsString
}
// 調(diào)用方式
join(lhsString: "hello", rhsString: "world", joiner: ",") // prints "hello,world" // 可以不使用快捷方式
func join(lhsString: String, rhsString: String, withJoiner joiner: String) -> String { return lhsString + joiner + rhsString
}
join("hello", "world", withJoiner: ",")// prints "hello,world" // 函數(shù)參數(shù)默認(rèn)值
// 參數(shù)參數(shù)可以提供默認(rèn)值,但是默認(rèn)值只能是參數(shù)列表的最后,也就是說
// 如果arg1提供默認(rèn)值,后面的都需要提供默認(rèn)值。
func join(#originalString: String, #destinationString: String, #withJoiner: String = " ") -> String { return originalString + withJoiner + destinationString
}
join(originalString: "hello", destinationString: "world", withJoiner: "-") // prints "hello-world"
join(originalString: "hello", destinationString: "world") // prints "hello world" // 如果提供了參數(shù)默認(rèn)值,Swift會自動把這個參數(shù)名也作為外部參數(shù)名
// 這里withJoiner相當(dāng)于加上了#:#withJoiner
func join(lhsString: String, rhsString: String, withJoiner: String = " ") -> String { return lhsString + withJoiner + rhsString
}
join("hello", "world", withJoiner: "-")// // prints "hello-world" // 可變參數(shù)
// 可變參數(shù)接受0個或者多個指定類型的值。可變參數(shù)使用...表示
// 函數(shù)最多只能有一個可變參數(shù),并且如果有可變參數(shù),這個可變參數(shù)必須出現(xiàn)在參數(shù)列表的最后
// 如果參數(shù)列表中有一或多個參數(shù)提供默認(rèn)值,且有可變參數(shù),那么可變參數(shù)也要放到所有最后一個
// 提供默認(rèn)值的參數(shù)之后(先是默認(rèn)值參數(shù),才能到可變參數(shù))
func arithmeticMean(numbers: Double...) -> Double { var total = 0.0 for number in numbers { total += number } return total / Double(numbers.count)
} arithmeticMean(1, 2, 3, ,4 5) // return 3.0
arithmeticMean(1, 2, 3) // return 2.0 // 常量和變量參數(shù)
// 在函數(shù)參數(shù)列表中,如果沒有指定參數(shù)是常量還是變量,那么默認(rèn)是let,即常量
// 這里Str需要在函數(shù)體內(nèi)修改,所以需要指定為變量類型,即用關(guān)鍵字var
func alignRight(var str: String, count: Int, pad: Character) -> String { let amountToPad = count - countElements(str) // 使用_表示忽略,因為這里沒有使用到 for _ in 1...amountToPad { str = pad + str } return str
} // 輸入/輸出參數(shù)
// 有時候,在函數(shù)體內(nèi)修改了參數(shù)的值,如何能直接修改原始實參呢?就是使用In-Out參數(shù)
// 使用inout關(guān)鍵字聲明的變量就是了
// 下面這種寫法,是不是很像C++中的傳引用?
func swap(inout lhs: Int, inout rhs: Int) { let tmp = lhs lhs = rhs rhs = tmp
}
// 如何調(diào)用呢?調(diào)用的調(diào)用,對應(yīng)的實參前面需要添加&這個符號
// 因為需要修改,所以一定是var類型的
var first = 3
var second = 4
// 這種方式會修改實參的值
swap(&first, &second) // first = 4, second = 3 // 使用函數(shù)類型
// 這里是返回Int類型
// 參數(shù)類型是:(Int, Int) -> Int
func addTwoInts(first: Int, second: Int) -> Int { return first + second
}
// 參數(shù)類型是:(Int, Int) -> Int
func multiplyTwoInts(first: Int, second: Int) -> Int { return first * second
} var mathFunction: (Int, Int) -> Int = addTwoInts
mathFunction(1, 2) // return 3
mathFunction = multiplyTwoInts
mathFunction(1, 2) // return 2 // 參數(shù)可以作為參數(shù)
func printMathResult(mathFunction: (Int, Int) -> Int, first: Int, second: Int) { println("Result: \(mathFunction(first, second))")
} printMathResult(addTwoInts, 3, 5) // prints "Result: 8"
printMathResult(multiplyTwoInts, 3, 5) // prints "Result: 15" // 函數(shù)作為返回類型
func stepForward(input: Int) -> Int { return input + 1
} func stepBackward(intput: Int) -> Int { return input - 1
} func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) { return backwards ? stepBackward : stepForward
} var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0) // call stepBackward() function // 參數(shù)可以嵌套定義,在C、OC中是不可以嵌套的哦
func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input + 1 } return backwards ? stepBackward : stepForward
}
使用函數(shù)類型
在 Swift 中,使用函數(shù)類型就像使用其他類型一樣。例如,你可以定義一個類型為函數(shù)的常量或變量,并將函數(shù)賦值給它:
?var mathFunction: (Int, Int) -> Int = addTwoInts
這個可以讀作:
“定義一個叫做?mathFunction?的變量,類型是‘一個有兩個?Int?型的參數(shù)并返回一個?Int?型的值的函數(shù)’,并讓這個新變量指向?addTwoInts?函數(shù)”。
addTwoInts?和?mathFunction?有同樣的類型,所以這個賦值過程在 Swift 類型檢查中是允許的。
函數(shù)類型作為參數(shù)類型也可以作為返回類型,如上代碼
?
轉(zhuǎn)載于:https://www.cnblogs.com/WJJ-Dream/p/5802935.html
總結(jié)
以上是生活随笔為你收集整理的Swift-函数的理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows下 sbulime tex
- 下一篇: Swift-闭包理解