클래스

손호준·2022년 6월 9일
0

swift

목록 보기
6/12

클래스

정의 문법

클래스는 참조 타입이며, 다중 상속이 불가능하고, 대문자 camel case를 사용하여 정의.

class 이름 {
	/*구현부*/
}

프로퍼티 및 메서드 구현

클래스에서는 구조체와 다르게 두가지 타입 메서드 존재. 상속 후 재정의가 가능한 class 타입 메서드, 상속 후 재정의가 불가능한 static 타입 메서드.

class Smaple {
	///인스턴스 프로퍼티///
	//가변 프로퍼티
    var mutableProperty: Int = 100
    
    //불변 프로퍼티
    let immutableProperty: Int = 100
    
    //타입 프로퍼티
    static var typeProperty: Int = 100
    
    ///인스턴스 메서드///
    func instanceMethod() {
    	print("intstnace method")
    }
    
    ///타입 메서드///
    //재정의 불가 타입 메서드 - static
    static func typeMethod() {
    	print("type method - static")
    }
    
    //재정의 가능한 타입 메서드 - class
    class func classMethod() {
    	print("type method - class")
    }
}

클래스 사용

//인스턴스 생성 - 참조정보 수정 가능
var mutableReference: Sample = Sample()

mutableReference.mutableProperty = 200

//불변 프로퍼티는 인스턴스 생성 후 수정 불가
//mutableReference.immutableProperty = 200

//인스턴스 생성 - 참조정보 수정 불가
let immutableReference: Sample = Sample()

//*클래스의 인스턴스는 참조 타입이므로 let으로 선언되었더라도 가변 인스턴스의 프로퍼티의 값 변경 가능*//
immutableReference.mutableProperty = 200

//하지만 참조정보는 변경 불가
//immutableReference = mutableReference

//참조 타입이라도 불변 인스턴스는 인스턴스 생성 후 수정 불가
immutableReference.immutableProperty = 200

//타입 프로퍼티 및 메서드
Sample.typeProperty = 300
Sample.typeMethod() //type method

//구조체와 마찬가지로 인스턴스에서는 타입 프로퍼티나 타입 메서드 사용불가
//mutableReference.typeProperty = 400
//mutableReference.typeMethod()
profile
Rustacean🦀/Data engineer💻

0개의 댓글