这章就以代码的方式记录了,力求做到:简洁、完整。
//带参数 返回值的函数
func sayHello(personName:String) ->String
{
let greeting ="Hello, " + personName +"!"
return greeting
}
print(sayHello("feng"))
//多个参数
func halfOpenRangeLength(start:Int, end:Int) ->Int
{
return end - start
}
print(halfOpenRangeLength(1, end:10))//9
//没参数到函数
func sayHelloWorld() ->String
{
return"Hello, world"
}
//没有返回值的函数-其实是返回特殊值void(是一个空元组())
func sayGoodBye(personName:String)
{
print("Goodbye,\(personName)")
}
//通过元组返回多个值
func minMax(array:[Int]) -> (min:Int, max:Int)
{
var currentMin = array[0]
var currentMax = array[0]
//array[1..<array.cout]返回范围内的值构成的新数组
for value in array[1..<array.count]{
if value < currentMin
{
currentMin = value
}else if value > currentMax
{
currentMax = value
}
}
return (currentMin, currentMax)
}
let bounds = inMax([8,-6,2,109,3,71])
print("min is\(bounds.min) and max is\(bounds.max)")
//min is -6 and max is 109
//可选元组返回类型,(Int,Int)?与元组包含可选属性如(Int?, Int?)不同。前者是整个元组是可选的
func minMaxOptional(array:[Int]) -> (min:Int, max:Int)? {
if array.isEmpty {returnnil}
var currentMin = array[0]
var currentMax = array[0]
//array[1..<array.cout]返回范围内的值构成的新数组
for value in array[1..<array.count]{
if value < currentMin
{
currentMin = value
}else if value > currentMax
{
currentMax = value
}
}
return (currentMin, currentMax)
}
if let bounds =minMaxOptional([8,-8,2,110,3,71])
{
print("min is\(bounds.min) and max is\(bounds.max)")
}
//min is -8 and max is 110
//外部参数名
func someFunction(to person:String, and anotherPerson:String)->String
{
return"Hello\(person) and\(anotherPerson)!"
}
print(someFunction(to:"feng", and:"liu"))//Hello feng and liu!
// 忽略第二个及后续的参数设置的参数名,用下划线(_)代替
func someFunction1(firstParameterName:Int,_ senondParameterName:Int)->Int
{
return firstParameterName + senondParameterName
}
//调用不需要参数名
print(someFunction1(2,2))//4
// 带默认参数的函数
func someFunction2(parameterWithDefault:Int =12)
{
print(parameterWithDefault)
}
someFunction2() //12
someFunction2(5)//5
/*使用(...)来定义可变参数接受0个或多个值
Double... 相当于 Double[]数组
函数最多有一个可变参数,为避免歧义一般写在参数列表的最后
如果函数有多个默认值,可变参数也放在参数列表最后
*/
func arithmeticMean(numbers:Double...) ->Double
{
var total:Double =0
for numberin numbers
{
total += number
}
return total / Double(numbers.count)
}
print(arithmeticMean(1,2,3,4,5))// 3.0
//函数默认参数为常量,不能更改值。
//用var声明一个可变参数(其生命周期只存在于函数体)
func alignRight(var string:String, totalLength:Int, pad:Character)->String
{
let amountToPad = totalLength - string.characters.count
if amountToPad < 1
{
return string
}
let padString = String(pad)
for_in1...amountToPad
{
string = padString + string
}
return string
}
let originalString ="hello"
let paddedString =alignRight(originalString, totalLength:10, pad: "-")
print(paddedString)//-----hello
//inout 定义输入输出参数
func swapTwoInts(inout a:Int,inout_ b:Int)
{
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 100
//传入参数是需要前面加"&",表示变量可以修改
swapTwoInts(&someInt, &anotherInt)
print("someInt:\(someInt),anotherInt:\(anotherInt)")//someInt:100,anotherInt:3
//函数类型(有函数参数类型和返回值类型组成)例如(Int,Int) -> Int
func addTwoInts(a:Int,_ b:Int)->Int
{
return a + b
}
func multiplyTwoInts(a:Int,_ b:Int)->Int
{
return a * b
}
func operatorIns(a:Int,_ b:Int,_ c:Int)->Int
{
return a + b + c
}
//函数赋值给变量
var mathFunction:(Int,Int)->Int =addTwoInts
print("Result:\(mathFunction(2,3))")//Result:5
mathFunction = multiplyTwoInts
print("Result:\(mathFunction(2,3))")//Result:6
//报错 参数不一样 mathFunction已经是Int,Int) -> Int
//mathFunction = operatorIns
//函数类型被swift推测
var anotherMathFunction =addTwoInts
print("anotherResult:\(anotherMathFunction(5,10))")//anotherResult:15
//函数类型作为参数
func printMathResult(mathFunction:(Int,Int)->Int,_ a:Int, _ b:Int)
{
print("Result:\(mathFunction(a,b))")
}
printMathResult(addTwoInts,3,5)//Result: 8
//函数作为返回类型(“—>”后写完整的函数类型(如(Int)-> (Int)))
func stepForward(input:Int) ->Int
{
return input +1
}
func stepBackward(input:Int) ->Int
{
return input -1
}
//返回一个函数
func chooseStepFunction(backward:Bool) -> (Int)->Int
{
return backward ?stepBackward :stepForward
}
/*嵌套函数
把函数定义在函数体中称为嵌套函数
对外不可见,可别他们的封闭函数调用。
封闭函数也可以返回他的一个嵌套函数
*/
func chooseStepFunction1(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 currValue = -4
let moveNearToZero = chooseStepFunction1(currValue > 0)
while currValue !=0 {
print("\(currValue)...")
currValue = moveNearToZero(currValue)
}
print("Zero!")
//-4...
//-3...
//-2...
//-1...
//Zero!