LoginSignup
31
23

More than 5 years have passed since last update.

Swiftの演算子を理解する

Last updated at Posted at 2015-12-21

Swiftの演算子についてまとめてみます。

Swiftの演算子は関数

+-*/==??と言った演算子は全て関数です。

public func +(lhs: Int, rhs: Int) -> Int
public func -(lhs: Int, rhs: Int) -> Int
public func *(lhs: Int, rhs: Int) -> Int
public func /(lhs: Int, rhs: Int) -> Int
public func ==(lhs: Int, rhs: Int) -> Bool
public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T

自分で作ったクラスの演算子を定義する

例えば自分で作ったクラスや構造体同士を==で比較したい場合は以下のように==メソッドを定義します。

struct MyStruct {
    let id: String
}
func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
    return lhs.id == rhs.id
}

MyStruct(id: "1") == MyStruct(id: "2") // → false
MyStruct(id: "1") == MyStruct(id: "1") // → true

独自の演算子を定義する

完全にオリジナルの演算子を定義したい場合は以下のように一度定義する必要があります。

infix operator *** {
    associativity none
    precedence 130
}
func ***(lhs: Int, rhs: Int) -> Int {
    return lhs * rhs
}

1 *** 1 + 1

precedenceは演算子の優先順位です。
値が大きい方が優先して計算されます。

infix operator *** {
associativity none
precedence 10
}
func ***(lhs: Int, rhs: Int) -> Int {
    return lhs * rhs
}

3 *** 1 + 1 // → 6(+のprecedenceは140なので***より先に計算される)

associativityは同じ優先度の演算子があった時に右と左のどちらを優先するかを決めれるものです。
left, right, noneの3種類があります。

infix operator *** {
associativity left
precedence 210
}
func ***(lhs: Int, rhs: Int) -> Int {
    return lhs * rhs
}

3 *** 1 *** 2 // noneの場合は同じ演算子のものが2つあるってエラーになる

++1のように先頭に付ける演算子はinfixの代わりにprefixを使います。
ここではassociativityやprecedenceを使えません。

prefix operator *** {
}
prefix func ***(lhs: Int) -> Int {
    return lhs * 10
}

***1

逆に末尾に付ける演算子ではpostfixを使います。

postfix operator *** {
}
postfix func ***(lhs: Int) -> Int {
    return lhs * 10
}

1***

それとassignmentという属性があったのですが、どんな効果があるかは分かりませんでした。
*=、+=などに付いているので代入が関わってくるとは思うのですが。

infix operator ***= {
assignment
}

使える記号

演算子に使える記号は以下になります。

/, =, -, +, !, *, %, <, >, &, |, ^, ?, ~
31
23
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
31
23