zoukankan      html  css  js  c++  java
  • 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)
    

      

  • 相关阅读:
    [转]HTTP请求模型和头信息参考
    括号匹配算法
    SQL LEFT JOIN 关键字 (转)
    Vim学习资料汇总
    与图相关的算法
    关于字符串的一些算法
    Huffman编码
    迅雷开放了下载引擎
    ubuntu下《UNIX环境高级编程》(apue.h)编译出错的处理方法
    学习unix信号
  • 原文地址:https://www.cnblogs.com/Rinpe/p/5054309.html
Copyright © 2011-2022 走看看