設定する
get-and-set
gettable および settable プロパティを実装する場合は、通常の構文を使用できます。ただし、プロパティget
を実装する場合は構文のみを使用できread-only
ます。あなたと一緒に財産setter
が与えられnewValue
ます。
class GetterSetter {
var theValue: Bool = false
var property: Bool {
get { return theValue }
set {
print("Value changed from \(theValue) to \(newValue)")
theValue = newValue
}
}
}
let getterSetter = GetterSetter()
getterSetter.property = true
getterSetter.property
// PRINTS:
// Value changed from 'false' to 'true'
したセット
didSet
プロパティオブザーバーは、プロパティが設定されたばかりのときにコードを実行する必要がある場合に使用されます。実装すると、前の値を表すdidSet
ことができます。oldValue
class DidSetter {
var property: Float16 = -1.0 {
didSet {
print("Value changed from \(oldValue) to \(property)")
}
}
}
let didSetter = DidSetter()
didSetter.property = 5.0
didSetter.property
// PRINTS:
// Value changed from -1.0 to 5.0
ウィルセット
willSet
プロパティオブザーバーは、プロパティが設定される前にコードを実行する必要がある場合に使用されます。実装willSet
するとnewValue
、新しいプロパティ値を表すことができます。
class WillSetter {
var property: String = "NO" {
willSet {
print("Value changed from \(property) to \(newValue)")
}
}
}
let willSetter = WillSetter()
willSetter.property = "YES"
willSetter.property
// PRINTS:
// Value changed from NO to YES