Swift 기본 개념- Immutability

aaaaa·2021년 10월 31일
0

Swift

목록 보기
2/2

Immutability

Variables announced with "var" are mutable, and the ones announced with "let" are immutable.

However, there's a difference between mutating a struct from the outside and changing a property from inside the struct.

ex) mutating outside a struct: appending a new property to a struct outside the struct

When trying to mutate a stuct's property inside itself, the following error message may pop up.

Cannot assign throught subscript: 'self'is immutable

This is because when referring to properties within a struct, "self"is automatically generated in front of the property, and it's defined with the "let" keyword.

In this case, we have to mark the method with the keyword "mutating".

struct School {
	var names: String
	var textbooks: [String : Int]

	init(names:String, textbooks:[String:Int]) {
		self.names = names.uppercased()
		self.textbooks = textbooks
}
	func addTextbooks() {
		// textbooks["History"] = 100 => error: "self" is immutable
		mutating textbooks["History"] = 100
	}
}


var mySchool = School(names:["Nami", "Hailey"], textbooks: ["Math":70])
mySchool.addTextbooks()

⚠️ If I write "let" instead of "var" to define "mySchool", the School struct and all its properties are immutable and I can't call a mutating function like addTextbooks.

0개의 댓글