Programming/iOS

[Swift] Cannot assign to property: 'self' is immutable

Space_Jin 2024. 5. 6. 17:32
728x90
๋ฐ˜์‘ํ˜•

Cannot assign to property: 'self' is immutable ๋ฌธ์ œ ์›์ธ๊ณผ ํ•ด๊ฒฐ

์œ„ ๋ฌธ์ œ๋Š” ๊ตฌ์กฐ์ฒด(Struct)์•ˆ์˜ property๋ฅผ ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด์„œ ๋ณ€๊ฒฝํ•˜๋ ค๊ณ  ํ•  ๋•Œ, ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ธฐ๋ณธ์ ์œผ๋กœ ๊ตฌ์กฐ์ฒด๋Š” ์Šค๋ƒ…์ƒท(snap shot)์„ ์ฐ์–ด๋‚ด๋Š” ๊ฒƒ์ด๋‹ค.

struct Example {
	var p = 0
    
    func changeP() {
    	p += 1	//p๋ฅผ 1์ฆ๊ฐ€
    }
}

์œ„ ์ฝ”๋“œ์—์„œ p๋Š” ๊ฐ€๋ณ€ ๋ณ€์ˆ˜๋กœ ์ •์˜ํ–ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ•ด๋‹น ๊ตฌ์กฐ์ฒด๋Š” ๋ณ€ํ•˜์ง€ ์•Š๋Š” ์Šค๋ƒ…์ƒท์ด ๋˜์–ด์•ผํ•˜๊ธฐ์— ๊ตฌ์กฐ์ฒด ์ž…์žฅ์—์„œ ๋ถˆ๋ณ€์ด์—ฌ์•ผํ•  property p๋ฅผ ๊ตฌ์กฐ์ฒด ๋‚ด๋ถ€ ํ•จ์ˆ˜์—์„œ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์—†๋‹ค.

var ex1 = Example()

ex1.p = 1	//p๊ฐ’์„ ๋ณ€๊ฒฝ

์œ„ ์ฒ˜๋Ÿผ Example์„ ์ƒ์†๋ฐ›์•„ ์ƒ์„ฑํ•œ ex1๊ฐ์ฒด๋Š” p๊ฐ’์„ ์ง์ ‘ ์ˆ˜์ •์€ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ, ๋””์ž์ธ ํŒจํ„ด์„ ์ง€ํ‚ค๊ธฐ ์œ„ํ•ด์„œ ๊ตฌ์กฐ์ฒด ๋‚ด๋ถ€ํ•จ์ˆ˜์—์„œ ๋ณ€๊ฒฝํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ํ•„์š”ํ•œ ์ƒํ™ฉ์ด ์ƒ๊ธด๋‹ค.

ํ•ด๊ฒฐ์ฑ… (mutating ํ‚ค์›Œ๋“œ ์‚ฌ์šฉ)

struct Example {
	var p = 0
    
    mutating func changeP() {
    	p += 1	//p๋ฅผ 1์ฆ๊ฐ€
    }
}

๋‚ด๋ถ€ property๋ฅผ ๋ณ€๊ฒฝํ•˜๊ธฐ ์œ„ํ•ด์„œ func ์•ž์— "mutating" ํ‚ค์›Œ๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ๋ณ€๊ฒฝ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

728x90
๋ฐ˜์‘ํ˜•