iOS/🟠 Swift

Computed Properties (계산 속성) - Properties

woozzang 2021. 2. 2. 17:16

"계산 속성"

 

계산 속성은 클래슀, ꡬ쑰체, μ—΄κ±°ν˜•μ—μ„œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 

값을 μ‹€μ œλ‘œ μ €μž₯ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

λ©”λͺ¨λ¦¬λ₯Ό μ°¨μ§€ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

 

λŒ€μ‹ ,  getter 와 μ„ νƒμ μœΌλ‘œ setter λ₯Ό μ œκ³΅ν•˜μ—¬ 그것듀을 μ΄μš©ν•΄ λ‹€λ₯Έ 속성을 μ‘°νšŒν•˜κ³  값을 κ°„μ ‘μ μœΌλ‘œ μ„€μ •ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

즉, κ³„μ‚°μ†μ„±μ—μ„œ setter μΆ”κ°€λŠ” μ„ νƒμ‚¬ν•­μž…λ‹ˆλ‹€.

λ˜ν•œ setter만 μ‘΄μž¬ν•˜λŠ” 계산 속성은 μ—†μŠ΅λ‹ˆλ‹€.

 

κΈ°λ³Έ 문법

struct Rect {
	...
    
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter) {
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
    
    ...
}

var newRect = Rect()
var newPoint: Point = newRect.center // getter 호좜됨
newRect.center = Point(5,5)          // setter 호좜됨

 

μ—¬κΈ°μ„œ κ³„μ‚°μ†μ„±μ˜ νƒ€μž…μ€ getter λΈ”λ‘μ˜ λ°˜ν™˜ νƒ€μž…μ„ μ˜λ―Έν•©λ‹ˆλ‹€.


 

Setter μΆ•μ•½ 문법

struct AlternativeRect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set {
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
}

 

setter λΈ”λ‘μ˜ νŒŒλΌλ―Έν„°λ₯Ό λͺ…μ‹œν•˜μ§€ μ•Šκ³  블둝 λ‚΄μ—μ„œ `newValue`  λΌλŠ” μƒμˆ˜λ₯Ό μ΄μš©ν•©λ‹ˆλ‹€.


 

Getter μΆ•μ•½ 문법

struct CompactRect {
    ...
    
    /* 1 */
    var center: Point {
        get {
            Point(x: origin.x + (size.width / 2),
                  y: origin.y + (size.height / 2))
        }
        set {
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
    
    /* 2 */
    var getOnlycenter: Point {
    
    	return Point(x: origin.x + (size.width / 2), y: origin.y + (size.height / 2))
    }
}

/* 1 */

getter 블둝이 ν•œ μ€„λ‘œ ν‘œν˜„λ˜λ©΄ `return` 을 μƒλž΅ν•©λ‹ˆλ‹€.

 

/*2 */

계산 속성이 getter 만 μžˆλ‹€λ©΄, `get { }` 을 μƒλž΅ν•©λ‹ˆλ‹€.

 

 

 

끝!