Swift学习函数和闭包

前端之家收集整理的这篇文章主要介绍了Swift学习函数和闭包前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit

var str = "Hello,playground"
//函数和闭包
//func  声明一个函数
func greet (name : String,day : String) ->String{

 return "hello \(name),today is \(day)"

}
greet("Bob","Friday")

func getGasPrices()->(Double,double,Double){

    return (3.59,3.69,3.79)
}
getGasPrices()

func sumof(numbers: Int...)->Int{
  var sum = 0
    for number in numbers{
      sum += number
    }

    return sum
}
sumof()
sumof(43,45,100)

func returnFifteen() ->Int{
  var y = 10
    func add(){
      y += 5
    }
    add()
    return y


}
returnFifteen()

func makeIncrementer() ->(Int ->Int){
    func addOne(numbew:Int)->Int{
      return 1 + numbew
    }
  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
}
var numbers = [20,19,7,12 ]
hasAnyMatches(numbers,lessThanTen)
//闭包
numbers.map({
    (number:Int) ->Int in
    let result  = 3 * number
    
    return result


})

numbers.map({number in 3 * number})

sort ([1,5,3,12,21]) {$0 > $1}

猜你在找的Swift相关文章