• Swift


    //: Playground - noun: a place where people can play
    
    import UIKit
    
    func add(a:Int, b:Int) -> Int
    {
        return a + b
    }
    
    // 其中, (Int, Int) -> Int 就是显式的声明函数类型
    let anotherAdd:(Int, Int) -> Int = add
    anotherAdd(3, 4)
    
    /*--------------------------------------------------------------------*/
    
    func sayHello(nickName:String)
    {
        print("Hello, (nickName)")
    }
    
    // 这里需要注意的是无返回值的函数类型的声明格式
    let anotherGreeting:(String) -> Void = sayHello
    anotherGreeting("Rinpe Chan")
    // 或者写成
    let greeting:(String) -> () = sayHello
    greeting("BoBo")
    // 或者写成(只有一个参数的时候有效)
    let anotherHello:String -> () = sayHello
    anotherHello("my son")
    
    /*------------------------------举个栗子--------------------------------*/
    
    // 假设老师要对两组学生的分数进行不同操作
    
    func changeScores1(inout scores:[Int]) {
        for index in 0..<scores.count {
            scores[index] += 3
        }
    }
    
    func changeScores2(inout scores:[Int]) {
        for index in 0..<scores.count {
            scores[index] -= 5;
        }
    }
    
    var scores1 = [36, 61, 78, 99, 100]
    changeScores1(&scores1)
    
    var scores2 = [12, 45, 76, 88, 96]
    changeScores2(&scores2)
    
    // 其实对于上面两个方法, 只是for循环里面的内容不同, 也就是老师对分数的操作
    // 可以简化为:
    
    func changeScores(op:(Int) -> Int, inout scores:[Int]) {
        for index in 0..<scores.count {
            op(scores[index])
        }
    }
    
    func op1(originScore:Int) -> Int {
        return originScore + 3
    }
    
    func op2(originScore:Int) -> Int {
        return originScore - 5
    }
    
    
    changeScores(op1, scores: &scores1)
    changeScores(op2, scores: &scores2)
    

      

  • 相关阅读:
    Linux文件管理系统
    添加硬盘分区
    SWPFILE实现(增加swap空间)
    磁盘配额
    javascript插件uploadify简单实现文件上传
    Java继承--子类的实例化过程
    Java继承--子父类中的构造函数
    Java继承--覆盖
    设计模式——单例设计模式
    在vim中,使用可视化拷贝(剪切)粘贴文本
  • 原文地址:https://www.cnblogs.com/Rinpe/p/5054309.html
Copyright © 2020-2023  润新知