Operator Identity Check
Swift 4.1, Xcode 9.3
I know that the ===
operator is used in Swift to check the identity of an operand. I have a situation whereby I want to check the identity of my operand against that of an operator – I need to check if my operation
parameter is +
or -
.
What I Want To Do
extension Collection where Element: Numeric {
func total(by operation: (Element, Element) -> Element) -> Element {
return (operation === + || operation === -) ? reduce(0, operation) : reduce(1, operation)
// For '+', '-', you need to use reduce with the initial value of 0
// For '*', '/', you need to use reduce with the initial value of 1
}
}
Point of clarification: I am wondering how to check the operation
's identity, but Swift only sees the operator as an operator rather than its underlying function.
Ideal Usage
let arr = [1, 2, 3, 4]
let totalSum = arr.total(by: +) //10
let totalProduct = arr.total(by: *) //24
Final Question
How do I check the identity of an operator
(refer to its underlying function)?