iOS ๐ŸŽ/Swift

Property Wrapper

yongmin.Lee 2022. 4. 28. 18:26

Property Wrapper

  • A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property. 
  • For example, if you have properties that provide thread-safety checks or store their underlying data in a database, you have to write that code on every property. When you use a property wrapper, you write the management code once when you define the wrapper, and then reuse that management code by applying it to multiple properties.
  • ์—ฌ๋Ÿฌ ํ”„๋กœํผํ‹ฐ๋“ค์— ๋™์ผํ•œ ๋กœ์ง์„ ์‹คํ–‰ํ•ด์•ผํ•˜๋Š”๊ฒฝ์šฐ ํ”„๋กœํผํ‹ฐ ๋ž˜ํผ๋ฅผ ์ •์˜ํ•˜๊ณ  ์—ฌ๋Ÿฌ ํ”„๋กœํผํ‹ฐ๋“ค์— ํ”„๋กœํผํ‹ฐ ๋ž˜ํผ๋ฅผ ์ ์šฉํ•˜์—ฌ ํ•ด๋‹น ๋กœ์ง์„ ์žฌ์‚ฌ์šฉํ• ์ˆ˜ ์žˆ๋‹ค.

 

์ •์˜ํ•˜๊ธฐ

  • To define a property wrapper, you make a structure, enumeration, or class that defines a wrappedValue property. 
  • The setter ensures that new values are less than or equal to 12, and the getter returns the stored value.
@propertyWrapper
struct TwelveOrLess {
    private var number = 0
    var wrappedValue: Int {
        get { return number }
        set { number = min(newValue, 12) }
    }
}

 

์‚ฌ์šฉํ•˜๊ธฐ

  • You apply a wrapper to a property by writing the wrapper’s name before the property as an attribute.
  • a structure that stores a rectangle that uses the TwelveOrLess property wrapper to ensure its dimensions are always 12 or less
struct SmallRectangle {
    @TwelveOrLess var height: Int
    @TwelveOrLess var width: Int
}

var rectangle = SmallRectangle()
print(rectangle.height)
// Prints "0"

rectangle.height = 10
print(rectangle.height)
// Prints "10"

rectangle.height = 24
print(rectangle.height)
// Prints "12"

 

์ดˆ๊ธฐ๊ฐ’ ์„ค์ •

  • SmallRectangle์— ์ดˆ๊ธฐ๊ฐ’ ์„ค์ •์„ ์ง€์›ํ•˜๊ณ  ์‹ถ์œผ๋ฉด property wrapper ์— ์ด๋‹ˆ์…œ๋ผ์ด์ €๋ฅผ ์ถ”๊ฐ€ํ•ด์ค˜์•ผํ•œ๋‹ค
@propertyWrapper
struct TwelveOrLess {
    private var number = 0
    var wrappedValue: Int {
        get { return number }
        set { number = min(newValue, 12) }
    }
    
    init() {
        
    }
    
    init(wrappedValue: Int) {
        number = min(wrappedValue, 12)
    }
}

struct SmallRectangle {
    @TwelveOrLess var height: Int = 2
    @TwelveOrLess var width: Int
}

var rectangle = SmallRectangle()
print(rectangle.height)
// Prints "2"

print(rectangle.width)
// Prints "0"

 

 

 

 

 

 

 

 

 

 

 

 

 

์ฐธ๊ณ ์ž๋ฃŒ

https://eunjin3786.tistory.com/472

https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID617