Struct란
struct Rectangle {
let width: Int
let height: Int
var area: Int {
return width * height
}
func isBiggerThan(_ rectangle: Rectangle) -> Bool {
return area > rectangle.area
}
}
- Struct의 이름은 항상 대문자로 시작 (ex.
Int
, Bool
등)
- Computed Property의 경우 property 값에 따라 계속 변경될 수 있으므로
var
사용
mutating
struct A {
var a: Int
func changeA(b: Int) {
a = b
}
}
- 자신의 Struct property 값을 변경하는 함수를 생성 할 경우
Cannot assign to property: 'self' is immutable.
에러 발생
- 에러를 제거하기 위해선 아래처럼 해당 함수 앞에
mutating
키워드를 붙여주어야 한다.
struct A {
var a: Int
mutating func changeA(b: Int) {
a = b
}
}
Struct와 Class의 차이점
Class: 참조 타입, Struct: 값 타입
class SimpleClass {
var count: Int = 0
}
var class1 = SimpleClass()
var class2 = class1
var class3 = class1
class3.count = 3
print(class1.count)
struct SimpleClass {
var count: Int = 0
}
var struct1 = SimpleStruct()
var struct2 = struct1
var struct3 = struct1
struct2.count = 2
struct3.count = 3
print(struct1.count)
print(struct2.count)
print(struct3.count)