swift - 数学符号作为函数参数

标签 swift

我能否以某种方式发送数学符号(+、-、*)作为函数参数?我想为不同的符号调用 reduce() 函数。

最佳答案

在 swift 中,符号是指定数学运算的函数名称。要将符号作为参数传递,参数类型必须是接受两个数字并返回一个数字的函数。如果您命令 + 单击任何标志,您将看到其定义如下:

public func +(lhs: UInt8, rhs: UInt8) -> UInt8

public func +(lhs: Int8, rhs: Int8) -> Int8

public func +(lhs: UInt16, rhs: UInt16) -> UInt16

public func +(lhs: Int16, rhs: Int16) -> Int16

public func +(lhs: UInt32, rhs: UInt32) -> UInt32

public func +(lhs: Int32, rhs: Int32) -> Int32

public func +(lhs: UInt64, rhs: UInt64) -> UInt64

public func +(lhs: Int64, rhs: Int64) -> Int64

public func +(lhs: UInt, rhs: UInt) -> UInt

public func +(lhs: Int, rhs: Int) -> Int

在您的情况下,您的 reduce 函数应如下所示

func reduce(sign: (Int,Int)->Int) -> Int{

    return sign(2,3)
}

reduce(*)
reduce(-)

关于swift - 数学符号作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496148/

相关文章:

ios - 当更改源为共享扩展时,@FetchRequest 结果未在 SwiftUI 中更新

ios - 在 UIView 类中添加 UIView 舍入逻辑

swift - 如何限制此等式最后一个字符串中的小数位数

swift - 如何在 Cocoa 中创建平移和缩放 Canvas (如 Photoshop)

快速四舍五入到最接近的第 n 位小数

xcode - 如何使用 UIAlertAction 处理程序 : 转到另一个 Storyboard

swift - 如何将应用程序的方向锁定为 iPhone 的纵向*仅*?

swift 2.2 : Type '()' does not conform to protocol 'BooleanType'

iOS 13 强制应用显示蓝牙权限提示

ios - UIImagePickerController swift 的问题