๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
iOS ๐ŸŽ/Swift

Swift08 - ๊ฐ’ ํƒ€์ž… vs ์ฐธ์กฐํƒ€์ž…

by yongmin.Lee 2021. 2. 1.

๊ฐ’ ํƒ€์ž…(Value Type)

  • ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌ ํ•  ๋•Œ ๊ฐ’์„ ๋ณต์‚ฌํ•˜์—ฌ ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค.
  • ๊ตฌ์กฐ์ฒด
  • ์—ด๊ฑฐํ˜•

๊ฐ’ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ

  • ์—ฐ๊ด€๋œ ๋ช‡๋ช‡์˜ ๊ฐ’๋“ค์„ ๋ชจ์•„์„œ ํ•˜๋‚˜์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์œผ๋กœ ํ‘œํ˜„ํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ
  • ๋‹ค๋ฅธ ๊ฐ์ฒด ๋˜๋Š” ํ•จ์ˆ˜ ๋“ฑ์œผ๋กœ ์ „๋‹ฌ๋  ๋•Œ ์ฐธ์กฐ๊ฐ€ ์•„๋‹ˆ๋ผ ๋ณต์‚ฌ(๊ฐ’ ๋ณต์‚ฌ) ํ•  ๊ฒฝ์šฐ
  • ์ž์‹ ์„ ์ƒ์†ํ•  ํ•„์š”๊ฐ€ ์—†๊ฑฐ๋‚˜, ๋‹ค๋ฅธ ํƒ€์ž…์„ ์ƒ์† ๋ฐ›์„ ํ•„์š”๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ
  • ์Šค์œ„ํ”„ํŠธ์˜ ๊ธฐ๋ณธ ๋ฐ์ดํ„ฐ ํƒ€์ž…์€ ๋ชจ๋‘ ๊ตฌ์กฐ์ฒด๋กœ ๊ตฌํ˜„๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.
  • ์Šค์œ„์ŠคํŠธ๋Š” ๊ตฌ์กฐ์ฒด์™€ ์—ด๊ฑฐํ˜• ์‚ฌ์šฉ์„ ์„ ํ˜ธํ•ฉ๋‹ˆ๋‹ค.
struct ValueType {
    var property = 1
}

// ์ฒซ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด ์ธ์Šคํ„ด์Šค
let firstStructInstance = ValueType()

// ๋‘ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด ์ธ์Šคํ„ด์Šค์— ์ฒซ ๋ฒˆ์งธ ์ธ์Šคํ„ด์Šค ๊ฐ’ ๋ณต์‚ฌ
var secondStructInstance = firstStructInstance

// ๋‘ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด ์ธ์Šคํ„ด์Šค ํ”„๋กœํผํ‹ฐ ๊ฐ’ ์ˆ˜์ •
secondStructInstance.property = 2

// ๋‘ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด ์ธ์Šคํ„ด์Šค๋Š” ์ฒซ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด๋ฅผ ๋˜‘๊ฐ™์ด ๋ณต์‚ฌํ•œ 
// ๋ณ„๋„์˜ ์ธ์Šคํ„ด์Šค์ด๊ธฐ ๋•Œ๋ฌธ์— 
// ๋‘ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด ์ธ์Šคํ„ด์Šค์˜ ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ๋ณ€๊ฒฝํ•ด๋„
// ์ฒซ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด ์ธ์Šคํ„ด์Šค์˜ ํ”„๋กœํผํ‹ฐ ๊ฐ’์—๋Š” ์˜ํ–ฅ์ด ์—†์Œ
print("first struct instance property : \(firstStructInstance.property)")    // 1
print("second struct instance property : \(secondStructInstance.property)")  // 2

 

 

์ฐธ์กฐ ํƒ€์ž…(Reference Type) :

  • ๋ฐ์ดํ„ฐ๋ฅผ ์ „ํ•  ํ•  ๋•Œ ๊ฐ’์˜ ๋ฉ”๋ชจ๋ฆฌ ์œ„์น˜๋ฅผ ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค.
  • ํด๋ž˜์Šค
  • Apple ํ”„๋ ˆ์ž„์›Œํฌ๋Š” ๋Œ€๋ถ€๋ถ„ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
class ReferenceType {
    var property = 1
}

// ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ํ›„ ์ฒซ ๋ฒˆ์งธ ์ฐธ์กฐ ์ƒ์„ฑ
let firstClassReference = ReferenceType()
// ๋‘ ๋ฒˆ์งธ ์ฐธ์กฐ ๋ณ€์ˆ˜์— ์ฒซ ๋ฒˆ์งธ ์ฐธ์กฐ ํ• ๋‹น
let secondClassReference = firstClassReference
secondClassReference.property = 2

// ๋‘ ๋ฒˆ์งธ ํด๋ž˜์Šค ์ฐธ์กฐ๋Š” ์ฒซ ๋ฒˆ์งธ ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค๋ฅผ ์ฐธ์กฐํ•˜๊ธฐ ๋•Œ๋ฌธ์—
// ๋‘ ๋ฒˆ์งธ ์ฐธ์กฐ๋ฅผ ํ†ตํ•ด ์ธ์Šคํ„ด์Šค์˜ ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๋ฉด
// ์ฒซ ๋ฒˆ์งธ ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค์˜ ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๊ฒŒ ๋จ
print("first class reference property : \(firstClassReference.property)")    // 2
print("second class reference property : \(secondClassReference.property)")  // 2