Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

property wrapper에 대해서 설명하시오. #27

Open Do-hyun-Kim opened 10 months ago

Do-hyun-Kim commented 10 months ago

property wrapper에 대해서 설명하시오.

Property wrapper란?

@propertyWrapper
struct Uppercase {
    private var value: String = ""
    var wrappedValue: String {
        get { return self.value }
        set { self.value = newValue.uppercased() }
    }

    // 필수 구현은 아님
    init(wrappedValue initialValue: String) {
        self.wrappedValue = initialValue
    }

}

struct Person {
    @Uppercase var name: String = "hyun" //Error: Argument passed to call that takes no arguments
    var age: Int = 11
}

var jenny: Person = Person()
print("jenny Name: \(jenny.name)")

@propertyWrapper
struct MaxLength {
    var wrappedValue: Int {
        didSet {
            self.wrappedValue = min(self.wrappedValue, 12)
        }
    }

    init(wrappedValue initialValue: Int) {
        self.wrappedValue = min(initialValue, 12)
    }
}

struct SmallRectangle {
    @MaxLength var height: Int
    @MaxLength var width: Int
}

var rectangle: SmallRectangle = SmallRectangle(height: 0, width: 0)
print("rect Height : \(rectangle.height)")
// print : 0

rectangle.height = 24
print("rect Height : \(rectangle.height)")
// print : 12

Property Wrapper 사용법

Property Wrapper 언제 사용하면 좋을까?

스크린샷 2023-11-05 오후 8 36 48

📝 참고 사이트

Hminchae commented 10 months ago

프로퍼티 래퍼 (Property Wrappers)

사용 예

var address = Address() address.city = "Lodon" print( address.city ) // LODON


- 연산프로퍼티 대신 프로퍼티 래퍼로 구현하여 사용
```swift
@propertyWrapper
struct FixCase {
    private(set) var value: String = ""

    var wrappedValue: String {
        get { value }
        set { value = newValue.uppercased() }
    }

    init(wrappedValue initiaValue: String) {
        self.wrappedValue = initiaValue
    }
}

struct Contact {
    @FixCase var name: String
    @FixCase var city: String
}

var contract = Contact(name: "Hwnag", city: "Seoul")
print(contract.name, contract.city)// HWNAG SEOUL

-> 모든 프로퍼티 래퍼는 값을 변경하거나 유효성을 검사하는 getter 와 setter 코드가 포함된 wrappedValue 프로퍼티를 가져야 함

참조

vichye-1 commented 10 months ago

property wrapper란?

사용법

property wrapper의 장점

참고

ronick-grammer commented 9 months ago

property wrapper란

property wrapper는 프로퍼티를 저장/반환하는 로직에 대해 공통성을 높여주고 반복성을 줄여주는 wrapper를 말한다.

@propertyWrapper
struct Uppercase {

    private var value: String = ""

    var wrappedValue: String {
        get { self.value }
        set { self.value = newValue.uppercased() }
    }

    init(wrappedValue initialValue: String) {
        self.wrappedValue = initialValue
    }
}

📝 참고 사이트