带有可选值的自定义运算符

时间:2018-03-31 05:36:22

标签: swift operators customization extension-methods optional

我是Swift的新手,正在为NSDecimalNumber制作自定义速记运算符:

// Non-Opt
static func + (left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.adding(right) }
static func - (left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.subtracting(right) }
static func * (left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.multiplying(by: right) }
static func / (left: NSDecimalNumber, right: NSDecimalNumber) -> NSDecimalNumber { return left.dividing(by: right) }

static func += (left: inout NSDecimalNumber, right: NSDecimalNumber) { left = left + right }
static func -= (left: inout NSDecimalNumber, right: NSDecimalNumber) { left = left - right }
static func *= (left: inout NSDecimalNumber, right: NSDecimalNumber) { left = left * right }
static func /= (left: inout NSDecimalNumber, right: NSDecimalNumber) { left = left / right }

// Optional
static func + (left: NSDecimalNumber?, right: NSDecimalNumber) -> NSDecimalNumber? { return left?.adding(right) }
static func - (left: NSDecimalNumber?, right: NSDecimalNumber) -> NSDecimalNumber? { return left?.subtracting(right) }
static func * (left: NSDecimalNumber?, right: NSDecimalNumber) -> NSDecimalNumber? { return left?.multiplying(by: right) }
static func / (left: NSDecimalNumber?, right: NSDecimalNumber) -> NSDecimalNumber? { return left?.dividing(by: right) }

static func += (left: inout NSDecimalNumber?, right: NSDecimalNumber) { left = left + right }
static func -= (left: inout NSDecimalNumber?, right: NSDecimalNumber) { left = left - right }
static func *= (left: inout NSDecimalNumber?, right: NSDecimalNumber) { left = left * right }
static func /= (left: inout NSDecimalNumber?, right: NSDecimalNumber) { left = left / right }

正如您所看到的,对于每个自定义函数,我都必须复制一个用于可选值。有没有办法合并选项和非可选项,所以它看起来不像重复的函数?

1 个答案:

答案 0 :(得分:1)

你可以将两者结合起来的原因是,在一个引擎盖下,一个Optional只是一个包含两个案例的枚举:什么都没有(见documentation)。因此,相同类型的非可选和可选是根本不同的。

但是,很多自定义运算符方法,尤其是+=-=等,都非常冗余。如果它们包含完全相同的实现,则无需保留这些非可选方法。您仍然可以将非选项传递给可选参数。

正如Sweeper在评论中所说,似乎通常的做法是不让自定义运算符包含可选参数。如果您担心重复问题,最好不要在前面进行检查。