函数和闭包

2016-12-01  本文已影响9人  陌上北辰

使用func 来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值的类型

func greet(name:String)->String{

return "hello \(name)"

}

调用

greet("xiaoming")

1)使用元组来让一个函数返回多个值。该元组的元素可以用名称或数字来表示

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)函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式

(写一个计算参数平均值的函数)

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)

上一篇 下一篇

猜你喜欢

热点阅读