參數
外部變量名
一般情況下你可以不指定外部變量名,直接調用函數:
func helloWithName(name: String, age: Int, location: String) {
println("Hello /(name). I live in /(location) too. When is your /(age + 1)th birthday?")
}
helloWithName("Mr. Roboto", 5, "San Francisco")
但是在類 (或者結構、枚舉) 中的時候,會自動分配外部變量名 (第一個除外) ,這時候如果還想直接調用就會報錯了:
class MyFunClass {
func helloWithName(name: String, age: Int, location: String) {
println("Hello /(name). I live in /(location) too. When is your /(age + 1)th birthday?")
}
}
let myFunClass = MyFunClass()
myFunClass.helloWithName("Mr. Roboto", 5, "San Francisco")
如果你懷念在 OC 中定義函數名的方式,可以繼續這樣定義,比如 helloWithName 這種,隱藏第一個函數的外部名:
class MyFunClass {
func helloWithName(name: String, age: Int, location: String) {
println("Hello /(name). I live in /(location) too. When is your /(age + 1)th birthday?")
}
}
let myFunClass = MyFunClass()
myFunClass.helloWithName("Mr. Roboto", age: 5, location: "San Francisco")
如果你實在不想要外部變量名,那么可以用 _ 來代替:
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius 是 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius 是 0.0
let bodyTemperature = Celsius(37.0)
// bodyTemperature.temperatureInCelsius 是 37.0
對外部參數名的嫻熟應用可以極好的抽象初始化過程。可以看看 json-swift library 中的應用。
默認參數值
可以在函數定義里寫上函數的默認值,這樣在調用的時候可以不傳這個值:
func add(value1 v1:Int, value2 p1:Int = 2) -> Int{
return v1 + p1
}
add(value1: 2, value2: 4) // 2 + 4
add(value1: 1) // 1 + 2
如果你沒有提供外部參數名,設置默認參數值會自動提供默認參數名。
可變參數
可變參數 (Variadic Parameters) 可以接受一個以上的參數值。比如計算平均數:
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers { // numbers is [Double]
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
arithmeticMean(3, 8, 19)
如果不止一個參數,需要把可變參數放在最后,否則會報錯。應該這樣:
func sumAddValue(addValue:Int=0, numbers: Int...) -> Int {
var sum = 0
for number in numbers { // numbers === [Int]
sum += number + addValue
}
return sum
}
sumAddValue(addValue: 2, 2,4,5) // (2+2) + (4+2) + (5+2) = 17
常量和變量參數
默認參數是常量,無法在函數體中改變參數值。我們可以 var 一個新的值就行操作,也可以直接在函數定義中加上 var 避免在函數體中定義新的變量。
比如這一個右對齊函數:
func alignRight(var string: String, count: Int, pad: Character) -> String {
let amountToPad = count - countElements(string)
if amountToPad < 1 {
return string
}
let padString = String(pad)
for _ in 1...amountToPad {
string = padString + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-") // "-----hello"
輸入輸出參數 (inout)
在函數體中對變量參數進行的修改并不會改變參數值本身,比如看這個例子:
func add(var v1:Int) -> Int {
return ++v1
}
var a = 1
add(a) // 2
a // 1
如果想通過函數修改原始值需要 inout ,但是這樣是錯誤的:
func add(inout v1:Int) -> Int {
return ++v1
}
var a = 1
add(a) // 2
a // 1
在傳入的時候,需要加上 & 標記:
func add(inout v1:Int) -> Int {
return ++v1
}
var a = 1
add(&a) // 2
a // 1
泛型參數類型
在此借用一下 objc.io 中的例子來演示泛型參數類型的使用:
// 交換兩個值的函數
func valueSwap<T>(inout value1: T, inout value2: T) {
let oldValue1 = value1
value1 = value2
value2 = oldValue1
}
var name1 = "Mr. Potato"
var name2 = "Mr. Roboto"
valueSwap(&name1, &name2) // 交換字符串
name1 // Mr. Roboto
name2 // Mr. Potato
var number1 = 2
var number2 = 5
valueSwap(&number1, &number2) // 交換數字
number1 // 5
number2 // 2
函數類型
在 Swift 中,函數翻身把歌唱,終于成了一等公民,和其他類型平起平坐。
變量
我們可以定義一個變量,這個變量的類型是函數類型:
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
let anotherMathFunction = addTwoInts
anotherMathFunction(1,2) // 3
參數
函數既然是類型的一種,那么顯然也是可以作為參數傳遞的:
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: /(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5) // 將參數2和參數3作為參數傳給參數1的函數
返回值
函數也是可以作為結果返回的。比如返回的值是一個參數為 Int 返回值為 Int 的函數,就是這樣定義:func foo() -> (Int) -> Int??梢钥聪旅孢@個具體的例子:
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0) // 根據參數返回 stepForward 或 stepBackward
println("Counting to zero:")
while currentValue != 0 {
println("/(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// 3...
// 2...
// 1...
// zero!
別名
用多了會發現在一大串 ()-> 中又穿插各種 ()-> 是一個非常蛋疼的事情。我們可以用 typealias 定義函數別名,其功能和 OC 中的 typedef 以及 shell 中的 alias 的作用基本是一樣的。舉個例子來看下:
import Foundation
typealias lotteryOutputHandler = (String, Int) -> String
// 如果沒有 typealias 則需要這樣:
// func luckyNumberForName(name: String, #lotteryHandler: (String, Int) -> String) -> String {
func luckyNumberForName(name: String, #lotteryHandler: lotteryOutputHandler) -> String {
let luckyNumber = Int(arc4random() % 100)
return lotteryHandler(name, luckyNumber)
}
luckyNumberForName("Mr. Roboto", lotteryHandler: {name, number in
return "/(name)'s' lucky number is /(number)"
})
// Mr. Roboto's lucky number is 33
嵌套
但是其實并不是所有的函數都需要暴露在外面的,有時候我們定義一個新函數只是為了封裝一層,并不是為了復用。這時候可以把函數嵌套進去,比如前面這個例子:
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
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue < 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
println("/(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
柯里化 (currying)
柯里化背后的基本想法是,函數可以局部應用,意思是一些參數值可以在函數調用之前被指定或者綁定。這個部分函數的調用會返回一個新的函數。
這個具體內容可以參見 Swift 方法的多面性 中 柯里化部分的內容。我們可以這樣調用:
class MyHelloWorldClass {
func helloWithName(name: String) -> String {
return "hello, /(name)"
}
}
let myHelloWorldClassInstance = MyHelloWorldClass()
let helloWithNameFunc = MyHelloWorldClass.helloWithName
helloWithNameFunc(myHelloWorldClassInstance)("Mr. Roboto")
// hello, Mr. Roboto
多返回值
在 Swift 中我們可以利用 tuple 返回多個返回值。比如下面這個例子,返回所有數字的范圍:
func findRangeFromNumbers(numbers: Int...) -> (min: Int, max: Int) {
var maxValue = numbers.reduce(Int.min, { max($0,$1) })
var minValue = numbers.reduce(Int.max, { min($0,$1) })
return (minValue, maxValue)
}
findRangeFromNumbers(1, 234, 555, 345, 423)
// (1, 555)
而返回值未必都是有值的,我們也可以返回可選類型的結果:
import Foundation
func componentsFromUrlString(urlString: String) -> (host: String?, path: String?) {
let url = NSURL(string: urlString)
return (url?.host, url?.path)
}
let urlComponents = componentsFromUrlString("http://why/233;param?foo=1&baa=2#fragment")
switch (urlComponents.host, urlComponents.path) {
case let (.Some(host), .Some(path)):
println("host /(host) and path /(path)")
case let (.Some(host), .None):
println("only host /(host)")
case let (.None, .Some(path)):
println("only path /(path)")
case let (.None, .None):
println("This is not a url!")
}
// "host why and path /233/param"
以上所述就是本文的全部內容了,希望大家能夠喜歡。