ぜのぜ

しりとりしようぜのぜのぜのぜ

33日目 in-outパラメータのproperty observer

日記

今日はあまりに暇だったので明るいうちから書いている.

今日書いたコード

struct Cup {
    var content: String {
        willSet {
            print("willSet:", newValue)
        }
        didSet {
            print("didSet:", content)
        }
    }
}

func replace(_ newContet: String, from oldContent: inout String) {
    print("before pouring")
    oldContent = newContet
    print("after pouring")
}

func doNothing(_ content: inout String) {}

var coffeeCup = Cup(content: "")
print("call replace")
replace("coffee", from: &(coffeeCup.content))
print("call doNothing")
doNothing(&(coffeeCup.content))
// => call replace
// => before pouring
// => after pouring
// => willSet: coffee
// => didSet: coffee
// => call doNothing
// => willSet: coffee
// => didSet: coffee

初めて知ったこと

オブザーバを持つプロパティをin-outパラメータとして関数に渡すと,関数の最後でwillSetdidSetが呼ばれる.これはin-outパラメータについては関数の最後で値が書き戻されるようになっているため.そうなっている理由はIn-Out Parametersに書かれていそうなのでその時が来たら読む.

If you pass a property that has observers to a function as an in-out parameter, the willSet and didSet observers are always called. This is because of the copy-in copy-out memory model for in-out parameters: The value is always written back to the property at the end of the function. For a detailed discussion of the behavior of in-out parameters, see In-Out Parameters. https://docs.swift.org/swift-book/LanguageGuide/Properties.html