Binary operator cannot be applied to operands

Recently, I have been reading "functional programming in fast." In the book, the author makes some Int extension to conform to the protocol Smaller. To get a complete picture of the idea of ​​the author, I copy the code to my own site, but it reports an error.

protocol Smaller {
    static func smaller() -> Self?
}

extension Int: Smaller {
    static func smaller() -> Int? {
      //reporting error: Binary operator "==" cann't be applied to type of Int.type and Int  
      return self == 0 ? nil : self / 2
    }
}

It seems that it is self == 0not allowed in the extension. Does anyone have an idea of ​​the reason.

+4
source share
1 answer

I don’t think you wanted to use a static function, since you need to create an instantiated integer and check if it is less.

So, there are 2 approaches:

  • Remove the statics from the function, and then call it as usual: let aInt = 4 aInt.smaller() //will be 2

  • ,

`

protocol Smaller {
  static func smaller(selfToMakeSmall: Self) -> Self?
}

extension Int: Smaller {
  static func smaller(selfToMakeSmall: Int) -> Int? {
    //reporting error: Binary operator "==" cann't be applied to type of Int.type and Int
    return selfToMakeSmall == 0 ? nil : selfToMakeSmall / 2
  }
}


let theInt = 4
Int.smaller(theInt)

`

, Generics

+1

Source: https://habr.com/ru/post/1623777/


All Articles