美文网首页Swift
Swift Functions and Closures(斯威夫

Swift Functions and Closures(斯威夫

作者: Air_w | 来源:发表于2019-06-01 17:18 被阅读0次

    目录
    1、Declare function(声明函数)
    2、Use a tuple to make a compound value(使用元组创建复合值)
    3、Functions can be nested(函数可以嵌套)
    4、Functions are a first-class type.This means that a function can return a another function as its value.(函数是一流的类型,这意味着函数可以返回另一个函数作为其值)
    5、A function can take another function as one of its arguments(函数可以将另一个函数作为其参数之一)
    6、Closures:functions are actually a special case of closures(闭包:函数实际上是闭包的一种特殊情况)

    1、Declare function(声明函数)

    使用func声明函数,通过在括号中使用参数列表跟随其名称来调用函数,使用->将函数的参数名称和返回类型区分开。

    /*
     Declear function.
     */
    func greet(person:String,day:String) -> String{
        return "Hello \(person), today is \(day)"
    }
    print(greet(person: "Bob", day: "Tuesday"))//Hello Bob, today is Tuesday
    
    

    默认情况下,函数使用其参数名称作为其参数的标签。在参数名称前写入自定义参数标签,或则写入_表明不使用参数标签

    /*
     Declear function.
     */
    func greet(_ person:String,day:String) -> String{
        return "Hello \(person), today is \(day)"
    }
    print(greet("Bob", day: "Tuesday"))//Hello Bob, today is Tuesday
    
    

    2、Use a tuple to make a compound value(使用元组创建复合值)

    使用元组创建复合值-例如,从函数返回多个值。元组的元素可以通过名称或数字来引用

    
    /*
     使用元组创建复合值-
     */
    func calculateStatistics(scores:[Int]) -> (min:Int,max:Int,sum: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(scores: [5,3,100,3,9])
    print(statistics.sum)//120
    print(statistics.max)//100
    

    3、Functions can be nested(函数可以嵌套)
    嵌套函数可以访问外部函数中声明的变量

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

    4、Functions are a first-class type.This means that a function can return a another function as its value.(函数是一流的类型,这意味着函数可以返回另一个函数作为其值)

    函数可以返回另一个函数作为其值

    
    func returnFifteen() -> ((Int) -> Int){
        
        func add(number :Int) -> Int{
            return number + 5
        }
        
        return add
    }
    
    print("y:\(returnFifteen()(5))")//y:10
    
    

    5、A function can take another function as one of its arguments(函数可以将另一个函数作为其参数之一)

    函数可以将另一个函数作为其参数之一

    
    
    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]
    let hasAnymatcher = hasAnyMatches(list: numbers, condition: lessThanTen)
    print("hasAnymatcher:\(hasAnymatcher)")//hasAnymatcher:true
    
    

    6、Closures:functions are actually a special case of closures(闭包:函数实际上是闭包的一种特殊情况)

    “函数”实际上是“闭包”的一种特殊情况:可以在以后调用的代码块。闭包中的代码可以访问创建闭包的作用域中可用的变量和函数,即使闭包在执行时处于不同的作用域(您已经看到了嵌套函数的示例)。您可以使用大括号{}来编写没有名称的闭包。使用in分离参数和从表达体中返回的类型。

    格式(全)

    var numbers = [20, 19, 7, 12]
    
    numbers.map({(number:Int) -> Int in
        let result = 3 * number
        return result
    })
    
    

    格式(可省略)

    var numbers = [20, 19, 7, 12]
    
    numbers.map({ number in
        3 * number
    })
    
    

    您可以按“编号”替代“参数”

    
    var numbers = [20, 19, 7, 12]
    numbers.map({ number in
        print("number:\(number)")
        3 * number
    })
    numbers.map({
        print("""
    使用"$"+"参数索引"替代参数number,$0:\($0)
    """)
        3 * $0
    })
    /*
     number:20
     number:19
     number:7
     number:12
     使用"$"+"参数索引"替代参数number,$0:20
     使用"$"+"参数索引"替代参数number,$0:19
     使用"$"+"参数索引"替代参数number,$0:7
     使用"$"+"参数索引"替代参数number,$0:12
     */
    
    

    当闭包是函数的唯一参数时,可以完全省略:"括号"

    
    var numbers = [20, 19, 7, 12]
    numbers.map{ number in
        print("number:\(number)")
        3 * number
    }
    numbers.map{
        print("""
    使用"$"+"参数索引"替代参数number,$0:\($0)
    """)
        3 * $0
    }
    /*
     number:20
     number:19
     number:7
     number:12
     使用"$"+"参数索引"替代参数number,$0:20
     使用"$"+"参数索引"替代参数number,$0:19
     使用"$"+"参数索引"替代参数number,$0:7
     使用"$"+"参数索引"替代参数number,$0:12
     */
    
    

    想要查看更多、更详细有料干货点击我https://pdliuw.github.io/

    未完待续。。。

    相关文章

      网友评论

        本文标题:Swift Functions and Closures(斯威夫

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