본문 바로가기

Swift/Deep dive!!

[Swift] private(set) var vs computed property | Read-Only 프로퍼티는 왜 사용할까?

728x90

 
요즘 열심히 현대자동차 부트캠프에서 주어진 키워드에 대해 공부를 하고 있습니다. 기존에 해왔던 방식으로 임무를 완수하거나 개발하게 된다면 늘 그래왔듯 익숙하고 편하지만 더 많이 배우고 싶어 다양한 시도를 하고 있습니다.. 학습 키워드는 OOP였습니다. 캡슐화는 당연히 필수였고, 늘 하던 방식으로 객체를 선언하다가
 
문득 든 생각.. private(set) vs computed property(연산 프로퍼티). 우선 read-only에 대해서..

Read-Only property란?

외부에서 임의대로 값을 변경하지 못하게 클래스나 구조체 내부 변수를 보호할 수 있습니다. Concurrent한 환경에서 concurrecy problems이 발생되지 않음으로 안정합니다. 외부에서 클래스 내부의 read-only 변수의 값은 직접 접근해서 변경할 수 없지만 읽기는 가능하다는 뜻입니다.

private(set) var vs computed property

class Card<Shape: CardShapeEnumProtocol, Number: CardNumberEnumProtocol> {
  // MARK: - Properties
  private let _number: Number
  private let _shape: Shape
  private var _appearance: Appearance
  
  // MARK: - Lifecycle
  init(number: Number, shape: Shape, appearance: Appearance) {
    self._number = number
    self._shape = shape
    self._appearance = appearance
  }
}

 
이 클래스가 있을 때 private let 변수들에 대해서 read-only를 통해 외부에서 값을 읽기만 하고 싶었습니다.. 원래대로라면 computed property를 사용했는데, 문득 private(set) var를 쓰는게 좋을지 computed property를 쓰면 좋을지 고민을 하게 되었습니다.
 

Card<Shape: CardShapeEnumProtocol, Number: CardNumberEnumProtocol> {
  ...
  private(set) var shape: Shape
  ...
}

let bicycleCard: Card<BicycleCardShapeType, ...>(...)
bicycleCard.shape // shape 값

 
private(set) var를 _shape에 사용할 경우 Card변수 외부에서는 값을 설정할 수 없지만, 값을 읽을 수는 있도록 해주는 접근 방식입니다.
 

Card<Shape: CardShapeEnumProtocol, Number: CardNumberEnumProtocol> {
  ...
  private let _shape: Shape
  var shape: Shape { //2 Computed-property
    _shape
  }
  ...
}

class pokerCard<PokerCardShapeType,....>(...)
pokerCard.sahpe // 포커 카드 모양 읽을 수 있습니다.

 
 
privagte let _shape에 대해 computed Property 또한 외부에서 값을 설정할 수는 없지만 반환된 값을 읽을 수 있습니다.


computed property로 get(읽기전용) or get, set 을 수행할 수 있는데 왜 private(set) 이 있는건지 의문을 품었습니다. private(set)의 역할은 충분히 computed property가 대체할 수 있으니까요.....
 
그럼에도 private(set) var가 있는 이유는.. property의 경우도 stored 프로퍼티, computed 프로퍼티로 나뉜 이유는 computed property는 무언가를 동적으로 계산 또는 여러 프로퍼티에 의존해서  computed된 결과를 출력하는데 초점이 맞춰졌다는 생각이 들었습니다. (private(set) 써야겠어요..)

728x90