在房产内使用时,willSet-didSetget-set之间有什么区别?

在我看来,它们都可以为属性设置值.什么时候,为什么,我应该使用willSet-didSet,什么时候使用get-set

我知道对于willSetdidSet来说, struct 是这样的:

var variable1 : Int = 0 {
    didSet {
        println (variable1)
    }
    willSet(newValue) {
    ..
    }
}

var variable2: Int {
    get {
        return variable2
    }
    set (newValue){
    }
}

推荐答案

何时以及为什么我应该使用willSet/didSet

  • willSet被称为before,值被存储.
  • 存储新值后立即调用didSet.

用输出考虑你的例子:


var variable1 : Int = 0 {
        didSet{
            print("didSet called")
        }
        willSet(newValue){
            print("willSet called")
        }
    }

    print("we are going to add 3")

     variable1 = 3

    print("we added 3")

输出:

we are going to add 3
willSet called
didSet called
we added 3

它的工作原理类似于前置/后置条件

另一方面,如果要添加只读属性,可以使用get:

var value : Int {
 get {
    return 34
 }
}

print(value)

value = 2 // error: cannot assign to a get-only property 'value'

Swift相关问答推荐

SON数组到属性

SWIFT并发:合并Taskgroup和AsyncStream?

NSApplication是否需要NSApplicationDelegate?

循环字典中的数组

允许为 self 分配新的 struct 值的理由是什么?

如何从 Swift 中隐藏 Objective-C 类接口的一部分?

UIButton 配置不更新按钮标题

如何在 SwiftUI 中获取视图的位置

SwiftUI 视图的默认成员初始化器 VS 自定义初始化器

使用列表的下一项更新相同的视图

持久化字符串列表属性 RealmSwift

在 Swift 5.5 中编写同步和异步函数

Apple 的自然语言 API 返回意外结果

What is "SwiftPM.SPMRepositoryError error 5"?

在swift 3中将文件保存在文档目录中?

如何快速判断设备方向是横向还是横向?

如何在 iOS Swift 中进行多线程、并发或并行?

快速在 LLDB 中使用 po

UIButton 标题左对齐问题 (iOS/Swift)

tableView 部分标题消失 SWIFT