Swift

swift: 연산 프로퍼티

소재훈 2022. 1. 21. 23:09

연산 프로퍼티는 실제 값을 저장하는 프로퍼티가 아니라 특정 상태에 따른 값을 연산하는 프로퍼티이다.

인스턴스 내/외부의 값을 연산하여 돌려주는 getter나 은닉화된 내부의 프로퍼티 값을 간접적으로 설정하는 setter의 역할을 할 수도 있다.

 

메서드를 두고 연산 프로퍼티를 사용하는 이유는 외부에서 메서드를 통해 인스턴스 내부의 값에 접근하려면 메서드를 두 개(getter, setter) 구현해야 하므로, 코드의 가독성이 나빠질 수 있다.

struct CoordinatePoint {
    var x: Int = 0
    var y: Int = 0
    
    var oppositePoint: CoordinatePoint {
        get {
            return CoordinatePoint(x: -x, y: -y)
        }
        
        set(opposite) {
            x = -opposite.x
            y = -opposite.y
        }
    }
}

var jaehoonPosition: CoordinatePoint = CoordinatePoint(x: 10, y: 20)
print(jaehoonPosition) //CoordinatePoint(x: 10, y: 20)
print(jaehoonPosition.oppositePoint) // CoordinatePoint(x: -10, y: -20)

setter의 매개변수로 원하는 이름을 소괄호 안에 명시 해주면 전달 인자로 사용할 수 있지만, newValue로 매개변수의 이름을 대신할 수 있다. 접근자 내부의 코드가 단 한 줄이고, 그 결괏값의 타입이 프로퍼티의 타입과 같다면 return 키워드를 생략할 수도 있다.

struct CoordinatePoint {
    var x: Int = 0
    var y: Int = 0
    
    var oppositePoint: CoordinatePoint {
        get {
            CoordinatePoint(x: -x, y: -y)
        }
        
        set {
            x = -newValue.x
            y = -newValue.y
        }
    }
}

 

굳이 프로퍼티를 설정해줄 필요가 없으면 setter를 없애서 읽기전용으로 연산 프로퍼티를 사용할 수도 있다. get 메서드만 사용해서 구현한다.

struct CoordinatePoint {
    var x: Int = 0
    var y: Int = 0
    
    var oppositePoint: CoordinatePoint {
        get {
            return CoordinatePoint(x: -x, y: -y)
        }
    }
}

'Swift' 카테고리의 다른 글

Swift: 타입 프로퍼티(Type Property)  (0) 2022.02.06
프로퍼티 감시자: Property Observers  (0) 2022.02.06
swift: 저장 프로퍼티  (0) 2022.01.21
swift: 구조체와 클래스의 차이  (0) 2022.01.21
swift: 클래스  (0) 2022.01.21