Geon

Swift의 Property Wrapper에 대해 설명해주세요. 본문

iOS developer essential skills

Swift의 Property Wrapper에 대해 설명해주세요.

jgkim1008 2024. 7. 9. 23:53

Property Wrapper를 사용하는 이유와 장점은 무엇인가요?

  • 중복되는 코드 구현을 막을수 있다.
  • 편리함

@State, @Binding, @ObservedObject 등의 Property Wrapper의 차이점과 사용 방법을 설명해주세요.

  • state는 View 내부에서 값의 변화를 통해 View를 업데이트 할떄 주로 사용합니다.
  • Binding은 부모 View 같이 외부 객체와 데이터를 연동시키기 위해 바인딩을 사용한다.
  • ObservedObject는 Observable을 할수 있는 객체의 변화를(내부 Published) 감지하고자 하는 값에 주로 선언한다.
  • StateObject는 한번의 init만 진행하고자 할때 주로 사용한다.

Custom Property Wrapper를 만드는 방법과 사용 예시를 들어주세요.

@propertyWrapper struct OnlyInputEnglish {
    private var value: String

    
    var wrappedValue: String {
        get { self.value}
        set { value = removeETC1(input: self.value) }
    }
    
    init (wrappedValue initValue: String) {
        self.value = initValue
    }
    
    private func removeETC(input: String) -> String {
        let pattern = "[^a-zA-Z]"
           
           // 정규 표현식 컴파일
           let regex = try? NSRegularExpression(pattern: pattern, options: [])
           
           // 매칭되는 부분을 빈 문자열로 대체
           let range = NSRange(location: 0, length: input.utf16.count)
           let modifiedString = regex?.stringByReplacingMatches(in: input, options: [], range: range, withTemplate: "") ?? ""
           
           return modifiedString
    }

}

 

  • 영어 이외에는 삭제되는 프로퍼티 래퍼를 생성