iOS

Swift ;; 클래스(Class), 구조체(Struct)

may_wonhui 2022. 4. 21. 19:22
  • Class(클래스)
    • 참조(Reference) 타입
      : 데이터 전달 시 메모리 위치를 전달 (원본이 변할 수 있음, c언어의 포인터 개념과 유사!)
    • 상속 가능

 

  •  Struct(구조체)
    • 값(Value) 타입
      : 데이터 전달 시 값을 복사하여 전달 (원본이 변할 수 없음)
    • 상속 불가

< 예시 코드>

/*struct*/
struct ValueType {
	var mutableProperty: Int = 100 //가변 프로퍼티
    let immutableProperty: Int = 200 //불변 프로퍼티
    
    static var typeProperty: Int = 300 //타입 프로퍼티
    
    static func typeMethod() { //타입 메서드
    	print("type method")
    }
}

//타입 프로퍼티,메서드 사용법 >> 구조체이름.타입프로퍼티/메서드 이름으로 접근 가능
print(ValueType.typeProperty) //300
ValueType.typeMethod() //type method

let firstStructInstance = ValueType()
//firstStructInstance.mutableProperty = 50 >> 에러) 불변 인스턴스이므로 가변 프로퍼티 변경도 불가능!!
var secondStructInstance = firstStructInstance
//secondStructInstance.immutableProperty = 35 >> 에러) 가변 인스턴스에서도 불변 프로퍼티는 변경이 불가능!!
secondStructInstance.mutableProperty = 1

print(firstStructInstance.mutableProperty) // 100
print(secondStructInstance.mutableProperty) //1 >> 값을 복사하여 전달하기 때문에 원본은 그대로 100



/*class*/
class ReferenceType {
	var mutableProperty: Int = 10 //가변 프로퍼티
    let immutable Property: Int = 20 //불변 프로퍼티
    
    static var typeProperty: Int = 30 //타입 프로퍼티

	static func typeMethod() { //재정의 불가 타입 메서드 - static
    	print("type method - static")
    }
    
    class func classMethod() { //재정의 가능 타입 메서드 - class
    	print("type method - class")
    }
}

let firstClassInstance = Referencetype()
firstClassInstance.mutableProperty = 11 //>>구조체와 달리 데이터의 위치를 넘기기에 불변 인스턴스에서 가변 프로퍼티 변경이 가능!!
var secondClassInstance = firstClassInstance
secondClassInstance.mutableProperty = 9

print(firstClassInstance.mutableProperty) //9
print(secondClassInstance.mutableProperty) //9 >>메모리의 위치를 전달하기 때문에 원본도 9로 변경

  • 클래스와 구조체의 공통점
    • 값을 저장하기 위한 프로퍼티를 정의할 수 있다. 
    • 기능 구현을 위한 메서드를 정의할 수 있다.
    • 초기값을 할당하기 위한 이니셜라이저를 정의할 수 있다. 
    • 새로운 기능 구현을 위해 확장될 수 있다.

 

  • 클래스가 가진 차이점
    • 상속이 가능하다. 
    • 클래스의 인스턴스에서는 타입 캐스팅이 가능하다. 
    • 클래스의 인스턴스에서는 디이니셜라이저를 활용할 수 있다. 
    • 클래스의 인스턴스에서는 참조값 계산이 허용된다. 

 

 

https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html