Swift -- 函数的使用(函数作为参数、返回值、嵌套函数)

前端之家收集整理的这篇文章主要介绍了Swift -- 函数的使用(函数作为参数、返回值、嵌套函数)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

// 函数作为返回值
func addTen(x: Int) -> (Int -> Int){
func getNum(num2: Int) -> Int{
return num2 + x
}
return getNum
}
var x = addTen(10)
print(x(20))

// 函数作为参数

func hasAnyMatches(list: [Int],condition: Int -> Bool) -> Bool{
for item in list{
if condition(item){
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool{
return number < 10
}
var numbers = [20,19,7,12]
hasAnyMatches(numbers,condition: lessThanTen)

// 返回Tuple(元组)的函数

func getTuple(arr: [Int]) -> (max: Int,min: Int,avg: Float,sum: Int)?{
if arr.count == 0{
return nil
}
var max: Int = arr[0]
var min: Int = arr[0]
var avg: Float = 0
var sum: Int = arr[0]
var index = 0
for item in arr{
index++
if item > max{
max = item
}
if item < min{
min = item
}
sum += item
}
avg = Float(sum / index);
return (max,min,avg,sum)
}
var arr = [9,11,3,-5,-13,99,30]
if let result = getTuple(arr){
print("max: \(result.max),min: \(result.min),avg: \(result.avg),sum: \(result.sum)")
}

// 可变参数func sum(nums: Int...) -> Int{ var sum = 0; for item in nums{ sum += item } return sum}var x = sum()var y = sum(9,10)var z = sum(1,5,9)// 函数嵌套func fifteen() -> Int{ var x = 10 func addFive(){ x += 5 } addFive() return x}var a = fifteen()

猜你在找的Swift相关文章