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 ์Šค์œ„ํ”„ํŠธ ํ”„๋กœ๊ทธ๋ž˜๋ฐ - ์•ผ๊ณฐ