美文网首页
基础知识七:函数

基础知识七:函数

作者: 随偑侕荇 | 来源:发表于2017-03-23 18:20 被阅读5次

    1.函数的定义

    //无参数、无返回值
    func function(){
    }
    
    //函数参数与返回值
    func function(person:String) -> String {
    }
    
    //多参数参数,带返回值
    func greet1(person:String,age:String) ->String{
        let greeting = "hello:" + person + "age:" + age
        return greeting
    }
    
    //函数参数,不带返回值
    func function(person:String) {
    }
    

    2.带多个返回值(以元组形式返回)

    func minMax(array:[Int]) ->(min:Int,max:Int) {
        var currentMin = array[0]
        var currentMax = array[0]
        for value in array{
            if value < currentMin {
                currentMin = value
            }
            else if value > currentMax{
                currentMax = value
            }
        }
        return (currentMin,currentMax)
    }
    

    3.函数参数标签和参数名称

    每个函数参数都有一个参数标签以及一个参数名称;

    参数标签:修饰参数名称,方便开发人员更好的读懂

    默认情况下,函数参数使用参数名称来作为它们的参数标签。

    //带有参数标签
    func function(name a:String) {
        print(a)
    }
    function(name: "faker")     //faker
    
    //忽略参数标签
    func function(_ a:String) {
        print(a)
    }
    function("faker")           //faker
    

    4.默认参数值

    给参数一个默认值;若没有传值的时候,使用默认值;有参数传递的时候,用使用实参

    func function(a:String = "faker") {
        print(a)
    }
    function()              //faker
    function22(a: "mata")           //mata
    

    5.输入输出参数

    函数参数默认下是常量。当在方法内需要改变形参的值时,需要使用inout关键字

    func swapTwoInts(_ a: inout Int, _ b: inout Int) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
    
    var someInt = 3
    var anotherInt = 107
    swapTwoInts(&someInt, &anotherInt)
    print("\(someInt), \(anotherInt)")  // 107, 3
    

    6.函数类型

    函数的类型由函数的参数类型和返回类型组成

    可以理解为定一个变量,指向函数

    func addTwoInts(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
    func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
        return a * b
    }
    // addTwoInts、multiplyTwoInts的函数类型为:(Int,Int) -> Int
    
    var mathFunction: (Int,Int) ->Int
    mathFunction = addTwoInts
    
    print(mathFunction(2,5))  //7
    
    mathFunction = multiplyTwoInts
    print(mathFunction(2,5)) //10
    
    //函数类型作为参数类型
    func printMathResult(_ mathfunction: (Int,Int) -> Int,_ a:Int,_ b:Int)
    {
        print(mathfunction(a,b))
    }
    
    printMathResult(mathFunction, 3, 4) //12
    
    

    极客学院 - 函数

    相关文章

      网友评论

          本文标题:基础知识七:函数

          本文链接:https://www.haomeiwen.com/subject/obytottx.html