Computed Properties (κ³μ° μμ±) - Properties
"κ³μ° μμ±"
κ³μ° μμ±μ ν΄λμ€, ꡬ쑰체, μ΄κ±°νμμ μ¬μ©ν μ μμ΅λλ€.
κ°μ μ€μ λ‘ μ μ₯νμ§ μμ΅λλ€.
λ©λͺ¨λ¦¬λ₯Ό μ°¨μ§νμ§ μμ΅λλ€.
λμ , 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 { }` μ μλ΅ν©λλ€.
λ!