0
1

More than 3 years have passed since last update.

Property Wrappersで値にアクセスしたら自動的に指定した値に戻る仕組みを作る

Posted at

SwiftのProperty Wrappersで値にアクセスしたら指定した値に戻る仕組みを作ってみました。

指定した値に戻るとはtrue -> falseOptional.some -> Optional.noneのようなことです。戻る値はProtocolで指定することができます。

私は例えば

  • エラーメッセージを表示したい場合に一度アクセスして表示したら次回は値が存在しなくなる
  • 画面遷移を発生させる時にtrueをセットしておいて、値アクセス後はfalseに自動で戻る

という様に利用しています。

値用Protocolの作成

まず戻る値を指定するProtocolを作成します。
以下のように、否定値として定義しました。

protocol Negatable {
    static var negativeValue: Self { get }
}

extension Bool: Negatable {
    static var negativeValue: Bool { false }
}

extension Optional: Negatable {
    static var negativeValue: Optional<Wrapped> { .none }
}

Property Wrappersの作成

次にその値に戻る仕組みをProperty Wrappersで作成します。
とても簡単な仕組みで、getしたら保存してある値をnegativeに変更するだけです。

@propertyWrapper
class Negativile<N: Negatable> {
    private var value: N = N.negativeValue

    var wrappedValue: N {
        get {
            let result = value
            value = N.negativeValue
            return result
        }
        set {
            value = newValue
        }
    }
}

使い方

以下のようなクラスを作成して利用してみると自動的に値が変更されているのが分かります。

class A {
    @Negativile var b: Bool
    @Negativile var s: String?
}

let a = A()
a.b = true
print(a.b)  // true
print(a.b)  // false
a.s = "test"
print(String(describing: a.s))  //Optional("test")
print(String(describing: a.s))  // nil
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