Swift 运算符作函数参数

可以将运算符(+ - * /)等,作为函数的参数,使用如下:

func operatorFun(left: T, right: T, combine: (T, T) -> T) -> T {
    return combine(left, right)
}
let letft: Int = 10
let right: Int = 8
print(operatorFun(left: letft, right: right, combine: +)) /// 18
print(operatorFun(left: letft, right: right, combine: -)) /// 2
print(operatorFun(left: letft, right: right, combine: *)) /// 80
print(operatorFun(left: letft, right: right, combine: /)) /// 1

你可能感兴趣的:(Swift 运算符作函数参数)