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 μŠ€μœ„ν”„νŠΈ ν”„λ‘œκ·Έλž˜λ° - μ•Όκ³°