swift中的函数用法,嵌套函数和返回一个函数以及函数作为参数,闭包

func  calculateStatistics(scores: [ Int ]) ->(min: Int ,max: Int ,sum: Int ){ //[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 , 100 , 3 , 9 ])
statistics .sum // 数组的用法
statistics . 2 // 数组快速下标

func  returnFifteen() -> Int { // 函数嵌套的示例
     var  y =  10
    
func  add(){
        y += 
5
    }
    
add ()
    
return  y
}
returnFifteen ()

func  makeIncrementer() -> ( Int  ->  Int ){ // 这里示范了如何返回函数的写法
     func  addOne(number:  Int ) -> Int {
        
return   1  + number
    }
    
return   addOne
}
var  increment =  makeIncrementer () // 接收函数
increment ( 7 )

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   // 快速语法返回一个 bool
}
var  numbers = [ 20 19 7 12 ]
hasAnyMatches ( numbers lessThanTen ) // 将函数作为参数传递进去

numbers . map ({ // 闭包的写法
    (number: Int ) ->  Int   in
    
let  result =  3  * number
    
return  result
})
let  mappedNumbers =  numbers . map ({number  in   3  * number}) // 上述闭包的快速写法
mappedNumbers

let  sortedNumbers =  sorted ( numbers ){ $0 > $1 } //$0 为快速位置引用
sortedNumbers
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值