// 有返回值
func len(start: Int, end: Int) -> Int {
return end - start
}
// 无返回值
func sayHello(name: String) {
println("Hello, \(name)")
}
// 多重返回值
func search(name: String) -> (id: Int, name: String) {
var map = ["jason": 1, "mark": 2]
return (name, map[name])
}
// 外部参数名
func join(str s1: String, toStr s2: String, joiner joiner: String) -> String {
return s1 + joiner + s2
}
join(str: "hello", toStr: "world", joiner: ",")
// 简写外部参数名
func join(#str: String, #toStr: String, #joiner: String) -> String {
return str + joiner + toStr
}
join(str: "hello", toStr: "world", joiner: ",")
// 默认参数
func join(str s1: String, toStr s2: String, joiner joiner: String = " ") -> String {
return str + joiner + toStr
}
join(str: "hello", toStr: "world")
// 默认带上外部参数
func join(s1: String, s2: String, joiner: String = " ") -> String {
return s1 + joiner + s2
}
join("hello", "world", joiner: "-")
// 可变参数
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// 函数参数默认是常量,不能改变,可以加var来定义变量参数
func hello(var str: String) -> String {
str += ",hello"
return str
}
// 改变参数值,加inout,且不能被var或let标记
func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt) // 传入时加&
println("\(someInt) and \(anotherInt)") // 107 and 3
// 使用函数
var mathFunction: (Int, Int) -> Int = addTwoInts
var anotherMathFunction = addTwoInts
// 函数作为参数
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// 函数作为返回值
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
}
// 嵌套函数
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
}