// Struct
struct Resolution {
var width = 0
var height = 0
}
// Class
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
// Instance
let someResolution = Resolution()
let someVideoMode = VideoMode()
- call by value (ํ ๋น ๋๋ ํ๋ผ๋ฏธํฐ ์ ๋ฌ์ value copy๊ฐ ์ผ์ด๋จ)
- stack memory ์์ญ์ ํ ๋น (์๋๊ฐ ๋น ๋ฆ)
- scope based lifetime: ์ปดํ์ผํ์์ compiler๊ฐ ์ธ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ํ ๋น/ํด์ ํ ์ง ์ ํํ ์๊ณ ์์
- data locality: CPU ์บ์ ํํธ์จ์ด ๋์
- ์์ ๋ถ๊ฐ๋ฅ (protocol์ ์ฌ์ฉ ๊ฐ๋ฅ)
- NSData๋ก serialize ๋ถ๊ฐ๋ฅ
- Codable ํ๋กํ ์ฝ์ ์ด์ฉํ์ฌ ์์ฌ์ด JSON <-> struct ๋ณํ ๊ฐ๋ฅ (Swift 4 ์ด์)
- ํญ์ ์๋ก์ด ๋ณ์๋ก copy๊ฐ ์ผ์ด๋๊ธฐ๋๋ฌธ์ multi-thread ํ๊ฒฝ์์ ๊ณต์ ๋ณ์๋ก ์ธํด ๋ฌธ์ ๋ฅผ ์ผ์ผํฌ ํ๋ฅ ์ด ์ ์
- call by reference (ํ ๋น ๋๋ ํ๋ผ๋ฉํฐ ์ ๋ฌ์ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๊ณ ์๋ ๋ฉ๋ชจ๋ฆฌ ์ฃผ์๊ฐ๋ง ๋ณต์ฌ๋จ)
- heap memory ์์ญ์ ํ ๋น (์๋๊ฐ ๋๋ฆผ)
- ๋ฐํ์์ ์ง์ allocํ๋ฉฐ reference counting์ ํตํด dealloc์ด ํ์
- memory fragmentation ๋ฑ์ overhead๊ฐ ์กด์ฌ
- ์์ ๊ฐ๋ฅ
- NSData serialize ๊ฐ๋ฅ
- Codable ์ฌ์ฉ ๋ถ๊ฐ๋ฅ
- ๋ฐํ์์ ํ์ ์บ์คํ ์ ํตํด์ ํด๋์ค ์ธ์คํด์ค์ ๋ฐ๋ผ ์ฌ๋ฌ ๋์์ด ๊ฐ๋ฅ
- deinitializer ์กด์ฌ
์ฐธ๊ณ : class์์ struct ๋ณ์๋ฅผ property๋ก ์ ์ํ๋๊ฒ์ ๊ฐ๋ฅํ๋ฉฐ, ๋ฐ๋๋ก struct์ property์ค ํ๋๋ก class ์ธ์คํด์ค ๋ณ์๋ฅผ ๊ฐ๊ณ ์๋ ๊ฒ๋ ๊ฐ๋ฅํ๋ค.
์ด ๊ฒฝ์ฐ ํด๋น struct ๋ณ์์ copy๊ฐ ์ผ์ด๋ ๋ class ์ธ์คํด์ค์ ์ฃผ์๊ฐ๋ง ๋ณต์ฌ๋๋ค.
call by value
VS call by reference
๊ตฌ์กฐ์ฒด(struct)์ ์ด๊ฑฐํ(enum)์ call by value
๋ก์, ํ ๋น ๋๋ ํ๋ผ๋ฏธํฐ ์ ๋ฌ ์ value copy๊ฐ ์ผ์ด๋๋ค.
ํ์ง๋ง Class๋ call by reference
๋ก์, ํ ๋น ๋๋ ํ๋ผ๋ฏธํฐ ์ ๋ฌ ์ value copy ๋์ ์ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๊ณ ์๋ ์ฃผ์๊ฐ๋ง ๋ณต์ฌ๋์ด ์ฐธ์กฐ๊ฐ ์ด๋ฃจ์ด์ง๋ค.
์ฐ๋ฆฌ๊ฐ ์ฌ์ฉํ๋ ๋ฐฐ์ด, ๋์ ๋๋ฆฌ, ์ ๊ณผ ๊ฐ์ ์ปฌ๋ ์ ํ์ ์ ๊ตฌ์กฐ์ฒด๋ก์ ๊ตฌํ๋์ด ์๋ค.