LoginSignup
0
1

More than 3 years have passed since last update.

Swiftでオブジェクトを比較する

Posted at

何回も見直してあまり頭に入っていないと感じたので、備忘録として記事にします。

Equatableを使う

Swiftでオブジェクトを比較するためにはEqutableを使えば可能です。

使用する目的

例えば2つの引数を構造体に与えて、片方だけの引数で比較してあげたいときに有効かと思います。

サンプル

・青のリンゴと赤のリンゴを同一のリンゴとして判定したい
・与えれる情報は、名前と色

// Equatableはオブジェクトが比較できることを保証する
struct Fruit: Equatable {
    var name: String
    var color: String

    // name のみの判定で結果を得たい時
    static func == (lhs: Fruit, rhs: Fruit) -> Bool {
        return lhs.name == rhs.name
    }
}

let gApple = Fruit(name: "Apple", color: "green")
let rApple = Fruit(name: "Apple", color: "red")

var result = gApple == rApple

print(result) // output: true

まとめ

かなりざっくりですが、具体的な用途があれば追記したいと思います。

0
1
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
0
1