funcminMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } elseif value > currentMax { currentMax = value } } return (currentMin, currentMax) }
let bounds = minMax([8, -6, 2, 109, 3, 71]) println("min is \(bounds.min) and max is \(bounds.max)") // prints "min is -6 and max is 109"
返回类型之可选元组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcminMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { returnnil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } elseif value > currentMax { currentMax = value } } return (currentMin, currentMax) }
iflet bounds = minMax([8, -6, 2, 109, 3, 71]) { println("min is \(bounds.min) and max is \(bounds.max)") } // prints "min is -6 and max is 109"
funccontainsCharacter(#string: String, #characterToFind: Character) -> Bool { for character in string { if character == characterToFind { returntrue } } returnfalse }
let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v") // containsAVee equals true, because "aardvark" contains a "v"
funcarithmeticMean(numbers: Double...) -> Double { var total: Double=0 for number in numbers { total += number } return total /Double(numbers.count) } arithmeticMean(1, 2, 3, 4, 5) // returns 3.0, which is the arithmetic mean of these five numbers arithmeticMean(3, 8.25, 18.75) // returns 10.0, which is the arithmetic mean of these three numbers
let originalString ="hello" let paddedString = alignRight(originalString, 10, "-") // paddedString is equal to "-----hello" // originalString is still equal to "hello"
输入输出形参:
1 2 3 4 5 6 7 8 9 10 11
funcswapTwoInts(inouta: Int, inoutb: Int) { let temporaryA = a a = b b = temporaryA }
var someInt =3 var anotherInt =107 swapTwoInts(&someInt, &anotherInt) println("someInt is now \(someInt), and anotherInt is now \(anotherInt)") // prints "someInt is now 107, and anotherInt is now 3"
函数类型
使用函数类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcaddTwoInts(a: Int, b: Int) -> Int { return a + b } funcmultiplyTwoInts(a: Int, b: Int) -> Int { return a * b }
var mathFunction: (Int, Int) -> Int= addTwoInts println("Result: \(mathFunction(2, 3))") // prints "Result: 5"
mathFunction = multiplyTwoInts println("Result: \(mathFunction(2, 3))") // prints "Result: 6"