如何返回Swift中的函数总和?

时间:2016-08-01 18:18:37

标签: swift

func studioTrackingCost(studioTrackingDays: Int, studioTrackingRate: Double) -> Double {
    return Double(studioTrackingDays) * studioTrackingRate
}

func studioOverdubCost(studioOverdubDays: Int, studioOverdubRate: Double) -> Double {
    return Double(studioOverdubDays) * studioOverdubRate
}

func studioMixingCost(studioMixingDays: Int, studioMixingRate: Double) -> Double {
    return Double(studioMixingDays) * studioMixingRate
}

1 个答案:

答案 0 :(得分:1)

不确定你在寻找什么,但如果你想定义一个接收所有6个参数的函数并返回3个函数的结果总和那么......

func tot(
    studioTrackingDays: Int, studioTrackingRate: Double,
    studioOverdubDays: Int, studioOverdubRate: Double,
    studioMixingDays: Int, studioMixingRate: Double
    ) -> Double {
    return
        studioTrackingCost(studioTrackingDays, studioTrackingRate: studioTrackingRate) +
        studioOverdubCost(studioOverdubDays, studioOverdubRate: studioOverdubRate) +
        studioMixingCost(studioMixingDays, studioMixingRate: studioMixingRate)

}

让我们发疯吧

让我们为函数接受的参数定义type alias

typealias ParamType = (Int, Double)

另一个type alias代表你的职能

typealias FunctionType = ParamType -> Double

现在我们可以定义一个接受元组列表的函数tot,其中每个tuple作为FunctionType类型的元素,另一个类型ParamType

func tot(elms: (logic: FunctionType, params: ParamType)...) -> Double {
    return elms.reduce(0) { (res, elm) -> Double in
        return elm.logic(elm.params)
    }
}

最后,我们可以调用tot向其传递可变数量的参数,如此

tot(
    (logic: studioTrackingCost, params: (1,2)),
    (logic: studioOverdubCost, params: (3,4)),
    (logic: studioMixingCost, params: (5,6))
)

或者

tot(
    (logic: studioTrackingCost, params: (1,2)),
    (logic: studioOverdubCost, params: (3,4))
)

或者

tot((logic: studioTrackingCost, params: (1,2)))