使用func 來(lái)聲明一個(gè)函數(shù),使用名字和參數(shù)來(lái)調(diào)用函數(shù)联贩。使用->來(lái)指定函數(shù)返回值的類型
func greet(name:String)->String{
return "hello \(name)"
}
調(diào)用
greet("xiaoming")
1)使用元組來(lái)讓一個(gè)函數(shù)返回多個(gè)值审孽。該元組的元素可以用名稱或數(shù)字來(lái)表示
funccalculate(scores: [Int])-> (min:Int,max:Int, sum:Int) {
var min= scores[0]?
var ? max= scores[0] ? ?var
sum =0
for score in scores {?
if score ?> max {
max= score??
? }else if score < min {
min =score;
}
2)函數(shù)可以帶有可變個(gè)數(shù)的參數(shù)翘鸭,這些參數(shù)在函數(shù)內(nèi)表現(xiàn)為數(shù)組的形式
(寫(xiě)一個(gè)計(jì)算參數(shù)平均值的函數(shù))
func calculateStatistics(scores:[Int])->(max:Int,min:Int,sum:Int){
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores{
if score ?> ?max{
max = score
}else if score < min{
min = score
}
sum += score
}
return(min,max,sum)
}
let statistics = calculateStatistics([5,3,10,3,9])
print(statistics)