iOS点滴记录

Swift 3.0学习笔记_1_元组&函数

2017-04-06  本文已影响25人  henu_Larva

1.元组<可返回多个值>

//元组<多个返回值>
func calculateStatustics(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
        }
        sum += score
    }
    return (min,max,sum)
}
let statistics = calculateStatustics(scores: [5,3,52,100,95])

获取到的元组数据可通过'点方法'或下标的方式取值

print(statistics.min)
print(statistics.max)
print(statistics.sum)

print(statistics.0)
print(statistics.1)
print(statistics.2)

2.可变参数个数的函数
2.1<求和函数>

func sumOf(numbers:Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(numbers: 1,2,3,4)

2.2<求平均值函数>

//计算平均值
func averageOf(numbers:Float...) -> Float {
    var sum :Float = 0
    for number in numbers {
        sum += number
    }
    //要做类型转换
    return sum/Float(numbers.count)
}
averageOf(numbers: 1,2,3,4)

3.函数作为参数进行传递

//函数作为参数传递
func hasAnyMatches(list:[Int],condition:(Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) { //condition 是传入的函数体
            return true
        }
    }
    return false
}
func lessThanTen(number:Int) -> Bool {
    return number < 10
}
var numbers = [20,19,7,12]
hasAnyMatches(list: numbers, condition: lessThanTen)
上一篇下一篇

猜你喜欢

热点阅读