说我有这样的代码
class MyClass {
bool isLoading = false;
String? errorMessage;
void fetchData() {
isLoading = true;
}
}
正如您在fetchData方法中看到的那样,我设置isLoading为true。
我想要的是……
每当我设置isLoading为 true时,errorMessage属性将自动设置为 null。isLoading所以在我设置为 true后,我不必手动将 null 值分配给 errorMessage 属性
// in a method
isLoading = true
errorMessage = null
// in another method
isLoading = true
errorMessage = null
// it is cumbersome to reassign error to be null over and over again after set isLoading to be true
isLoading = true
errorMessage = null
在 Swift 中,我可以通过使用称为属性观察器的东西来做到这一点
var errorMessage : String?
var isLoading: bool {
didSet {
if (isLoading == true) {
errorMessage = null
}
}
}