函数定义与调用(Defining and Calling Functions)@H_502_1@
函数参数与返回值(Function Parameters and Return Values)@H_502_1@
函数参数名称(Function Parameter Names)@H_502_1@
//: Playground - noun: a place where people can play@H_502_1@
import UIKit@H_502_1@
// \()是用来替换变量值@H_502_1@
func sayHello(personName: String ) -> String {@H_502_1@
let greeting = "Hello,\(personName)"@H_502_1@
return greeting@H_502_1@
}@H_502_1@
print(sayHello("luopan"))@H_502_1@
func sayHello() ->String {@H_502_1@
return "hello,swift!"@H_502_1@
}@H_502_1@
print(sayHello())@H_502_1@
func sayHello(personName:String,alreadyGreed:Bool)->String{@H_502_1@
if alreadyGreed{@H_502_1@
return sayHello("第二次\(personName)")@H_502_1@
}else{@H_502_1@
return sayHello("第一次\(personName)")@H_502_1@
}@H_502_1@
}@H_502_1@
print(sayHello("luopan",alreadyGreed: false))@H_502_1@
print(sayHello("luopan",alreadyGreed: true))@H_502_1@
//定义返回元祖,从而达到返回多个值的效果@H_502_1@
func minMax(array:[Int]) -> (min:Int,max:Int){@H_502_1@
var currentMin = array[0]@H_502_1@
var currentMax = array[0]@H_502_1@
for value in array[1..<array.count]{@H_502_1@
if value < currentMin {@H_502_1@
currentMin = value@H_502_1@
}else if value > currentMax{@H_502_1@
currentMax = value@H_502_1@
}@H_502_1@
}@H_502_1@
return (currentMin,currentMax)@H_502_1@
}@H_502_1@
let bounds = minMax([6,-2,4,456,3,78])@H_502_1@
print("min is \(bounds.min) and max is \(bounds.max)")@H_502_1@
//定义可选性元祖作为返回@H_502_1@
func minMax(array:[Double]) -> (min:Double,max:Double)?{@H_502_1@
var currentMin = array[0]@H_502_1@
var currentMax = array[0]@H_502_1@
@H_502_1@
for value in array[1..<array.count]{@H_502_1@
if value < currentMin {@H_502_1@
currentMin = value@H_502_1@
}else if value > currentMax{@H_502_1@
currentMax = value@H_502_1@
}@H_502_1@
}@H_502_1@
return(currentMin,currentMax)@H_502_1@
}@H_502_1@
//那么我们使用的时候需要解包可选型@H_502_1@
if let minMaxValue = minMax([23.34,-34,78,45.56,545.00,333.444]){@H_502_1@
print("min is \(minMaxValue.min) and max is \(minMaxValue.max)")@H_502_1@
}@H_502_1@
//定义一个具有外部参数名和局部变量名的函数@H_502_1@
func sayHello(to person:String,and anotherPerson:String) ->String{@H_502_1@
return "Hello \(person) and \(anotherPerson)"@H_502_1@
}@H_502_1@
//注意,如果指定了外部参数变量名,那么调用的时候,必须带上的。@H_502_1@
print(sayHello(to: "luopan",and: "mingxing"))@H_502_1@
func arithmeticMean(numbers:Double...) -> Double{@H_502_1@
var total:Double = 0@H_502_1@
for number in numbers{@H_502_1@
total += number@H_502_1@
}@H_502_1@
@H_502_1@
return total/Double(numbers.count)@H_502_1@
}@H_502_1@
print(arithmeticMean(1,2,5))@H_502_1@
print(arithmeticMean(3,8.26,18.75))@H_502_1@
今天到此为止吧!@H_502_1@