0

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)?


Community
  • 1
  • 1
Noah Wilder
  • 1,656
  • 20
  • 38
  • 2
    You need to use parenthesis in order to treat an operator as a function, e.g `(+)`. You cannot check the identity of functions though, as the results may not be what you expect, for example the compiler might have put them through thunks or specialised them. Compare https://stackoverflow.com/q/24111984/2976878 – Hamish May 15 '18 at 16:44
  • Also in your case, you would get different results from passing `+` to `total(by:)` vs. passing `{ $0 + $1 }`, which would be very surprising. – Hamish May 15 '18 at 16:45
  • @Hamish, how do you suggest I fix this? – Noah Wilder May 15 '18 at 17:26
  • 1
    You could hack it by checking if `operation(0, 1) == 0` and using 1 as the base if it is which would at least work for +,-,/,*. – dan May 15 '18 at 18:36

0 Answers0