LoginSignup
29
28

More than 5 years have passed since last update.

Swiftで新しい演算子を定義する

Last updated at Posted at 2014-06-06
Swift


class MyNumber {
    var value = 0
    init(value: Int) {
        self.value = value
    }
}

let a = MyNumber(value:3)
let b = MyNumber(value:5)

infix operator ^-^ { }

func ^-^(lhs: MyNumber, rhs: MyNumber) -> MyNumber{
    return MyNumber(value: lhs.value + rhs.value)
}

// 結果は8
let c = a ^-^ b

infix operator ** { }

func **(lhs: Double, rhs: Double) -> Double {
    return pow(lhs, rhs)
}

// 結果は25
let d = 5.0 ** 2.0


使えるのは以下のものだけのようですね
/ = - + * % < > ! & | ^ . ~

29
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
28