Swift

//: Playground - noun: a place where people can play

import UIKit

/*---------------------------返回函数类型-----------------------------*/
// 其实就是将函数当为返回值返回

func tier1MailFee(weight:Int) -> Int {  // 第一种邮费计算方式
    return 1 * weight
}

func tier2MailFee(weight:Int) -> Int {  // 第二种邮费计算方式
    return 2 * weight
}

// 计算最终价格, price为单价, weight为重量
func totalPrice(price:Int, weight:Int) -> Int {
    
    // 外部没办法调用chooseMailFeeCalcMethod这个函数
    // 通过判断重量, 来选择使用哪种邮费计算方式
    func chooseMailFeeCalcMethod(weight:Int) -> (Int) -> Int {
        return weight <= 10 ? tier1MailFee : tier2MailFee
    }
    
    let mailFeeCalc:(Int) -> Int = chooseMailFeeCalcMethod(weight)
    return mailFeeCalc(weight) + price * weight
}

totalPrice(5, weight: 10)

  

原文地址:https://www.cnblogs.com/Rinpe/p/5054465.html