Struct, Class

Joohyun·2022년 3월 3일
0

Struct란

  • 여러 value들을 하나로 묶어주는 역할
struct Rectangle {
	// Property
    let width: Int
    let height: Int
    
    // Computed Property
    var area: Int {
        return width * height
    }
    
    // Method
    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: 참조 타입
class SimpleClass { 
	var count: Int = 0 
} 

var class1 = SimpleClass() 
var class2 = class1 
var class3 = class1 
class3.count = 3 

// class3의 값을 변경했지만 참조타입이므로 class1도 변경 됨
print(class1.count) // 3
  • Struct: 값 타입
struct SimpleClass { 
	var count: Int = 0 
} 

var struct1 = SimpleStruct() 
var struct2 = struct1 
var struct3 = struct1 

struct2.count = 2 
struct3.count = 3 

// 구조체는 값 타입이므로 항상 새로운 메모리가 할당 됨
print(struct1.count) // 0 
print(struct2.count) // 2
print(struct3.count) // 3
profile
IOS Developer

0개의 댓글