[Grammer] 25 - Operator Methods

in swift4 •  6 years ago 
  • Operator Methods
static func operator(parameters) -> ReturnType {
   Code
}
struct Position {
   var x : Double
   var y : Double
}
extension Position {
   static func ==(left: Position, right: Positon) -> Bool {
      return left.x == right.x && left.y == right.y
   }
   static func !=(left: Position, right: Position) -> Bool {
      return !(left == right)
   }
}

let a = Position(x: 1, y: 2)
let b = Position(x: 3, y: 4)
a == b // false
a != b // true


extension Position {
   static prefix func -(pos: Position) -> Position {
      return Position(x: -pos.x, y: -pos.u)
      }
   static postfix func ++(pos: inout Position) -> Position {
      let ret = pos
      pos.x += 1
      pos.y += 1
      return ret
   }
}
var a = Position(x: 1, y: 2)
var result = -a
dump(result)

result = a++
dump(result)
dumpt(a)
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!