๐Ÿ”ธproperty observer (willSet/didSet)

โ•ฑ๐Ÿšง under construction ->

Swift โŸฉ type โŸฉ property โŸฉ stored โŸฉ property observer

  • Property observers are called every time a propertyโ€™s value is set, even if the new value is the same as the propertyโ€™s current value.

    • willSet is called just before the value is stored.

    • didSet is called immediately after the new value is stored.

  • You can add property observers in the following places:

struct Example {
    
    // โญ๏ธ stored property
    var value: Int = 0 {
    
        // โญ๏ธ property observer examples
        
        willSet {
            // โญ๏ธ willSet ้šฑๅซไธ€ๅ€‹ newValue ่ฎŠๆ•ธ๏ผŒๆŒ‡ๅณๅฐ‡่ฆ่ฎŠๆ›ด็š„ๆ–ฐๅฑฌๆ€งๅ€ผ
            print("value ๅณๅฐ‡่ขซ่จญๅฎš็‚บ \(newValue)")
        }
        
        // ---------------------------------------
        
        // ็‹€ๆณไธ€๏ผšๅชๅš็ด€้Œ„๏ผŒไธๅšไปปไฝ•ไฟฎๆ”น
        didSet {
            // โญ๏ธ didSet ้šฑๅซไธ€ๅ€‹ oldValue ่ฎŠๆ•ธ๏ผŒ็”จไพ†ๅญ˜ๅ–่ˆŠ็š„ๅฑฌๆ€งๅ€ผ
            print("value ๅพž \(oldValue) ๆ”น็‚บ \(value)")
        }
        
        // ็‹€ๆณไบŒ๏ผš้™คไบ†็›ฃๆŽงๅค–๏ผŒๅ†ๅšไฟฎๆ”น
        // (ๅฆ‚ๆžœๆ˜ฏ้€™็จฎๆƒ…ๆณ๏ผŒๅฏ่€ƒๆ…ฎ็”จ computed property (get/set))
        didSet {
            if value < 3 {
                print("value ๅฐๆ–ผ 3๏ผŒ่‡ชๅ‹•่ชฟๆ•ด็‚บ 3")
                // โญ๏ธ didSet ๅ…งๅฏ้‡ๆ–ฐ่จญๅฎšๅฑฌๆ€งๅ€ผ๏ผŒ
                // โ—๏ธ ไฝ†ไธๆœƒๅ†่งธ็™ผ didSet๏ผŒไปฅๅ…็„ก้™ๅพช็’ฐใ€‚
                value = 3
            }
        }
        
    }// value
}

Last updated

Was this helpful?