๐Ÿ”ฐcomputed property (get/set)

accessorโ•ฑgetter/setterโ•ฑ๐Ÿšง -> keyword "let"

Swift โŸฉ type โŸฉ property โŸฉ computed property

โš–๏ธ stored vs. computed

  • ๅฑฌๆ€งๆฒ’ๆœ‰ๅฏฆ้š›ๅ„ฒๅญ˜็š„ๅ€ผ๏ผŒๅ€ผๆ˜ฏๅ‹•ๆ…‹่จˆ็ฎ—็š„ใ€‚

computed property ็š„ๅ„ชๅ‹ข๏ผš

  • get ๏ผšๅฏๅ‹•ๆ…‹่จˆ็ฎ—ไธฆๅ‚ณๅ›žๅฑฌๆ€งๅ€ผใ€‚

  • set ๏ผšๅฏๆ””ๆˆชๅฑฌๆ€ง่ฎŠๆ›ด๏ผŒๆชขๆŸฅๆˆ–่ชฟๆ•ดๅ…ถๅ€ผ๏ผŒไฟ่ญทๅ…ง้ƒจ็‹€ๆ…‹ใ€‚

โš–๏ธ willSet/didSet vs. get/set

  • computed property ไนŸ็จฑ็‚บ accessorใ€‚

  • computed property ไธ€ๅฎš่ฆ็”จ var ๅฎฃๅ‘Šใ€‚

struct Circle {

    var radius: Double
    
    // โญ๏ธ computed property
    var area: Double { .pi * radius * radius }    // โญ๏ธ (implicit) get only
}

// ๅˆฉ็”จ computed property ไพ†็ขบไฟๅฑฌๆ€งๅ€ผ็š„็ฏ„ๅœ
struct NoLessThanThree {

    // inner state
    private var _value: Int = 3

    // โญ๏ธ computed property
    var value: Int {
        get { _value }
        set { _value = max(newValue, 3) }    // ็ขบไฟๆ•ธๅ€ผไธๅฐๆ–ผ 3
    }
}

// ่จป๏ผšๅฆ‚ๆžœๅˆๅง‹ๅŒ–ๅพŒๅฑฌๆ€งๅ€ผๅฐฑไธ่ฎŠ๏ผŒๅฏ่€ƒๆ…ฎไปฅไธ‹ๅšๆณ•๏ผš
struct Example {

    // (stored property) private set/internal get (get OK/no set!)
    private(set) var value: Int

    init(value: Int) {
        self.value = max(value, 3)          // ็ขบไฟๆ•ธๅ€ผไธๅฐๆ–ผ 3
    }
}

๐Ÿ“ ๆธฌ่ฉฆ

// ๆธฌ่ฉฆ
var num = NoLessThanThree()
num.value = 5      
num.value = 2      // value ่ขซ setter ่ชฟๆ•ด็‚บ 3 โญ๏ธ 
print(num.value)   // 3

Last updated