LoginSignup
6
1

More than 5 years have passed since last update.

Swiftで排他的論理和(XOR)

Last updated at Posted at 2017-06-20

概要

Swiftで排他的論理和(XOR)を算出する方法
xor.png

実現方法

Int型の場合

Int
let x = 1
let y = 1
let xor = x ^ y

Bool型の場合

Bool
let x = true
let y = true
let xor = (x != y)
// let x = true ? 1 : 0
// let y = true ? 1 : 0
// let xor = x ^ y

Bool値を用いた算出は存在しないようなので一旦Intに変換しつつ算出する必要がある。
コメントにて指摘頂きました。Boolのxorには!=が使えます。

サンプルケース

UICollectionViewを使って下記のような表現を行う際に用いました。
sample.png

サンプルコード

sample
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    let isDeepLine = 27..<54 ~= indexPath.row
    let isDeepColumn = 3..<6 ~= (indexPath.row % 9)
    let isDeep = (isDeepLine != isDeepColumn)
    cell.backgroundColor = isDeep ? .darkGray : .lightGray
    return cell
}

おわりに

&&||の組み合わせを使うよりもスッキリとしたコードで条件を書くことが出来ました。
誤りやより良い方法などありましたら、コメント/編集リクエスト頂けると助かります。
[追記]
コメントにて新たな知見を得ることが出来ました。tkhpさんありがとうございます!

6
1
1

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