LoginSignup
1
1

More than 5 years have passed since last update.

[Swift] で a == 1 && b == 2 && c == 3 を真にする[おまけつき]

Posted at

完全に乗り遅れたけど作りました

protocol Incrementable {
    mutating func increment()
}
extension Int: Incrementable {
    mutating func increment() {
        self = self + 1
    }
}

class A<T> where T: Incrementable, T: Equatable {

    var value: T
    init(_ value: T) {
        self.value = value
    }
    static func == (lhs: A<T>, rhs: T) -> Bool {
        defer { lhs.value.increment() }
        return lhs.value == rhs
    }
}

let a = A(1)

if a == 1 && a == 2 && a == 3 {
    print("俺が副作用だ!")
}

無駄にややこしいです!!

おまけ

ジェネリクスなのでこんなこともできるよ

extension Character: Incrementable {
    mutating func increment() {
        if let c = unicodeScalars.first?.value {
            self = Character(UnicodeScalar(c + 1)!)
        }
    }
}

let c = A(Character("a"))

if c == "a" && c == "b" && c == "c" {
    print("俺も副作用だ!")
}
1
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
1
1