// 函数作为返回值
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, 0, 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()
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。