M
M
max228122021-07-05 15:46:02
Swift
max22812, 2021-07-05 15:46:02

How to override Swift operator?

I have enum which is implemented as optional. I need it to add in one function, and subtract in the second and return this optional as well. How can I override operator functions to use in my enum?

enum Optional1 {
    case none
    case some(Int)
}

func plus (n1: Optional1l, n2: Optional1) -> Optional1 {
    return n1 + n2
}
func minus (n1: Optional1l, n2: Optional1) -> Optional1 {
    return n1 - n2
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-07-05
@vabka

extension Optional1 {
  static func +(left: Optional1, right: Optional1) -> Optional1 {
      // Тут реализуем сложение
  }
  static func -(left: Optional1, right: Optional1) -> Optional1 {
    // Тут реализуем вычитание
  }
}

https://medium.com/swift-india/everything-about-op...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question