概要
実現方法
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
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さんありがとうございます!