swift3-11 函数

函数定义

Swift 定义函数使用关键字 func。 定义函数的时候,可以指定一个或多个输入参数和一个返回值类型。 每个函数都有一个函数名来描述它的功能。通过函数名以及对应类型的参数值来调用这个函数。函数的参数传递的顺序必须与参数列表相同。 函数的实参传递的顺序必须与形参列表相同,-> 后定义函数的返回值类型。

示例:

func hello(name:String)-> String{
    return "Hello " + name
}

hello(name: "Jack")    


func hello1(name:String?)-> String{
    return "Hello " + (name != nil  ? name! : "guess")
}

hello1(name: "Jack")


func printHello(){
    print("hello")
}
printHello()

func printHello1() -> Void{  //Void 是一个类型
    print("hello")
}
printHello1()

func printHello2() -> (){
    print("hello")
}
printHello2()    

使用元组作为返回值 函数返回值的类型可以是字符串,整型,浮点型等,元组与数组类似,不同的是,元组中的元素可以是任意类型,使用的是括号,你可以使用元组类型让多个值作为一个复合值从函数中返回。

func findMaxAndMin(numbers:[Int]) -> (max:Int, min:Int)?{ //如果你不确定返回的元组一定不为nil,那么你可以返回一个可选的元组类型。
    guard !numbers.isEmpty else {
        return (Int.max,Int.min)
    }
    var minValue = numbers[0]
    var maxValue = numbers[0]
    for num in numbers{
        minValue = minValue < num ? minValue : num
        maxValue =  maxValue > num ? maxValue : num
    }
    return (maxValue ,minValue)
}
var numbers = [1,23,34,2,2,31,23,23,34,45,454545,4,54,5,45,45,45]
var result =  findMaxAndMin(numbers: numbers)
print(result?.max ?? 0,result?.min ?? 0)  
if let result =  findMaxAndMin(numbers: numbers) {
    print( result.max,result.min)
}

函数的内部参数和外部参数

func sayHelloTo(name:String, msg:String)-> String{
    return "\(msg), \(name)"
}
sayHelloTo(name: "a", msg: "b")  //sayHelloTo("a", msg: "b") 这种方式已被废弃

//内部参数和外部参数
func sayHelloTo(name:String, withMessage msg:String)-> String{
    return "\(msg), \(name)"
}
sayHelloTo(name: "a", withMessage: "b")

//修改外部参数名
func sayHello(to name:String, withMessage msg:String)-> String{
    return "\(msg), \(name)"
}
sayHello(to : "a", withMessage: "b")

//隐藏调用参数
func mutiply(_ num1:Int, _ num2:Int) -> Int{
    return num1*num2
}
mutiply(2,  4) 

默认参数值

func sayHello(to name:String, withMessage msg:String = "hello")-> String{
    return "\(msg), \(name)"
}
sayHello(to : "a", withMessage: "b")
sayHello(to: "jack") //可以省略后面的一个参数


func sayHello(to name:String, withMessage msg:String = "hello", punctuation:String = "!")-> String{
    return "\(msg), \(name) \(punctuation)"
}
sayHello(to : "a", withMessage: "b")
sayHello(to: "jack")
sayHello(to: "Jack", withMessage: "Hello")

可变参数值 一个函数至多只可以有一个变长的参数

//常用的变长参数函数
print("a","b","c")
//求平均值
func mean(numbers:Double ...) ->Double{
    var sum : Double = 0
    for num in numbers{
        sum += num
    }
    return sum / Double(numbers.count)
}
mean(numbers: 1,2,3,4,5,5.0,23,434)

常量参数,变量参数和 inout 参数 默认的函数参数都是常量。

func toBinary(num:Int)->String{ //直接声明称 var 类型参数已被废弃。
    var num = num  
    var res = ""
    repeat{
        res = String(num%2) + res
        num /= 2
    }while num != 0
    return res
}
toBinary(num: 1000)

//inout 
func toBinary( num:inout Int)->String{
    var res = ""
    repeat{
        res = String(num%2) + res
        num /= 2
    }while num != 0
    return res
}
var num = 100
toBinary(num: &num) //传入指针
print(num) 

//交换两个字符串
func swapTwoString(str1:inout String, str2:inout String){
    let tstr = str1
    str1 = str2
    str2 = tstr
}

var str1 = "a"
var str2 = "b"
swapTwoString(str1: &str1, str2:&str2)
str1
str2

函数型变量

func add(a:Int, b:Int) -> Int{
    return a + b
}

let add01 = add
add01(3,4)
let add02:(Int, Int) -> Int = add
add02(4,5)


var arr:[Int] = []
for _ in 0...100{
    arr.append(Int(arc4random()%1000))
}

arr.sort { (a, b) -> Bool in
    return a < b
}
arr

func descending (a:Int ,b:Int) ->Bool{
    return a > b
}
arr.sorted(by: descending)

函数变成初步

func changeScores( scors: [Int], by method:(Int)-> Int) -> [Int]{
    var arr = scors
    for (index , score) in scors.enumerated(){
        arr[index] = method(score)
    }
    return arr
}
func changeScore01 (score : Int) -> Int{
    return score + 3
}

func changeScore02 (score : Int) -> Int{
    return Int(Double(score)/150.0*100.0)
}

var arr:[Int] = []
for _ in 0..<10{
    arr.append(Int(arc4random())%150)
}
arr
changeScores(scors: arr, by: changeScore01)
changeScores(scors: arr, by: changeScore02)
//map 
arr.map(changeScore01)
func isPassOrFail(score:Int)->String{
    return score < 60 ? "Fail": "Pass"
}
arr.map(isPassOrFail)

//filter 过滤
func fail (score:Int)-> Bool{
    return score < 60
}
arr.filter(fail)

//reduce 聚合
func add(a:Int, b:Int)-> Int{
    return a + b
}
arr.reduce(0, add)

arr.reduce(0, +)

//Swift中,运算符号 本质上就是一个函数 
public func +(lhs: Int, rhs: Int) -> Int
public func *(lhs: Int, rhs: Int) -> Int
public func -(lhs: Int, rhs: Int) -> Int
public func /(lhs: Int, rhs: Int) -> Int
public func %(lhs: Int, rhs: Int) -> Int


func concatenate(str:String , num:Int) -> String{
    return "\(str)\(num) "
}
arr.reduce("", concatenate)

返回函数类型和函数嵌套

//邮递费用
func tilerMailfeeByWight( weight : Int) -> Int{
    return 1*weight
}
func tiler2MailfeeByWight( weight : Int) -> Int{
    return 3*weight
}
//超过10单位,则按三倍计算
func feeBytUnitPrice (price :Int , wight:Int) -> Int{
    py
    func chooseMailFeeCalationByWeight(weight: Int) -> (Int) -> Int{
        return weight <= 10 ? tilerMailfeeByWight : tiler2MailfeeByWight
    }

    let mailFeefuc = chooseMailFeeCalationByWeight(weight: wight)
    return mailFeefuc(wight) + price*wight //邮递费用+商品费用
}
feeBytUnitPrice(price: 2, wight: 11)