-
Computed Properties (๊ณ์ฐ ์์ฑ) - PropertiesiOS/๐ 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 { }` ์ ์๋ตํฉ๋๋ค.
๋!
'iOS > ๐ Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] - Subscripts (์๋ธ์คํฌ๋ฆฝํธ) (0) 2021.02.19 Access Control (์ ๊ทผ ์ ์ด) (0) 2021.02.17 Adopting a Protocol Using a Synthesized Implementation - Protocols (0) 2021.01.27 [Swift] Delegation (0) 2021.01.26 Checking Type & Downcasting - Type Casting (0) 2021.01.21