ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Computed Properties (๊ณ„์‚ฐ ์†์„ฑ) - Properties
    iOS/๐ŸŸ  Swift 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 { }` ์„ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.

     

     

     

    ๋!


     

    ๋Œ“๊ธ€

์–ด์ œ๋ณด๋‹ค ๋ฐœ์ „ํ•œ ๋‚˜