Swift
[Swift] μ°μ° νλ‘νΌν°λ‘ κ°λ μ± λμ΄κΈ°!
yevdev
2022. 3. 19. 13:42
π‘μ°μ° νλ‘νΌν°?
μ€μ κ°μ μ μ₯νλ νλ‘νΌν°κ° μλλΌ, νΉμ μνμ λ°λ₯Έ κ°μ μ°μ°νλ νλ‘νΌν°
λ©μλλ‘ μ κ·Όμμ μ€μ μλ₯Ό ꡬννλκ²μ μ°μ° νλ‘νΌν°λ₯Ό μ¬μ©νλ©΄ μ½λμ κ°λ μ±μ λμΌ μ μλ€!
λ€λ§, get λ©μλλ§ κ΅¬νν΄λ κ²μ²λΌ μ½κΈ° μ μ© μνλ‘λ ꡬννκΈ° μ½μ§λ§, μ°κΈ° μ μ© μνλ‘λ ꡬνν μ μλ€λ λ¨μ μ΄ μλ€.
μ°μ° νλ‘νΌν° μ μμ μ¬μ©
struct CoordinatePoint{
var x: Int // μ μ₯ νλ‘νΌν°
var y: Int // μ μ₯ νλ‘νΌν°
var oppositePoint: CoordinatePoint{ // μ°μ° νλ‘νΌν°
// μ κ·Όμ
get {
return CoordinatePoint(x: -x, y: -y)
}
// μ€μ μ
set(opposite){
x = -opposite.x
y = -opposite.y
}
}
}
var yejinPosition: CoordinatePoint = CoordinatePoint(x: 19, y: 20)
print(yejinPosition) // 10, 20
print(yejinPosition.oppositePoint) // -10, -20
// λμΉμ’νλ₯Ό (15, 20)μΌλ‘ μ€μ ν΄λλ©΄
yejinPosition.oppositePoint = CoordinatePoint(x:15, y: 25)
// νμ¬ μ’νλ -15, -25λ‘ μ€μ λλ€.
print(yejinPosition) // -15, -25
newValueλ‘ λ§€κ°λ³μ μ΄λ¦μ μλ΅ν μ€μ μ
struct CoordinatePoint{
var x: Int // μ μ₯ νλ‘νΌν°
var y: Int // μ μ₯ νλ‘νΌν°
var oppositePoint: CoordinatePoint{ // μ°μ° νλ‘νΌν°
// μ κ·Όμ
get {
// μ΄κ³³μμ return ν€μλλ₯Ό μλ΅ν μ μλ€.
return CoordinatePoint(x: -x, y: -y)
}
// μ€μ μ
set {
x = -newValue.x
y = -newValue.y
}
}
}
Reference
Swift μ€μννΈ νλ‘κ·Έλλ° - μΌκ³°