Eddie
Eddie

Reputation: 1941

Custom operator with optional values

I'm new to Swift, and was making custom shorthand operator for NSDecimalNumber like this:

// 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 }

As you can see, for every custom function, I'll have to duplicate one for optional values. Is there a way to merge option and non-optional so it doesn't look like duplicated functions?

Upvotes: 2

Views: 242

Answers (1)

tktsubota
tktsubota

Reputation: 9401

The reason you can't combine the two is that, under the hood, an Optional is just an enumeration with two cases: nothing and something (see documentation). Therefore, a non-optional and optional of the same type are fundamentally different.

However, a lot of your custom operator methods, especially the +=, -=, etc., are very redundant. There is no need to keep around those non-optional methods if they contain the exact same implementation. You can still pass in non-optionals into optional parameters.

As Sweeper said in the comments, it seems to be common practice to not have custom operators contain optional arguments. You might be better off nil-checking up front if you are that concerned about duplication.

Upvotes: 1

Related Questions