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)
    

      

  • 相关阅读:
    Eclipse EE 3.6 failed to create the java virtual machine 解决
    [收藏]家用三线插座(220V单相)正确接线方法
    Java设计模式 Design Pattern:包装模式 Decorator Pattern
    MIME 类型列表
    面试题参考
    循环队列的运用求K阶斐波那契序列
    加密技术仿射密码
    面试题集锦_1
    栈的运用(5)转换逆波兰式
    栈的运用(6)逆波兰式求值
  • 原文地址:https://www.cnblogs.com/Rinpe/p/5054309.html
Copyright © 2011-2022 走看看