본문 바로가기
iOS/Swift 문법 심화 학습

클래스 [ Class ]

by 황민우 2022. 2. 3.

정의

- 클래스를 정의하여 객체를 만들고 사용할 수 있습니다.

- 클래스에서 생성된 객체, 인스턴스를 만들어 코드 내에서 사용할 수 있습니다.

- 클래스는 구조체와 유사합니다.

- Swift의 클래스는 다중 상속이 되지 않습니다.

- 클래스는 참조 타입입니다.


정의 형식

class 이름 {
	// 구현코드
}

예제

- 클래스도 구조체와 유사하게 프로퍼티와 메서드를 구현할 수 있습니다.

클래스 생성

- 클래스에서는 두 가지의 타입 메서드가 있습니다.

- 두 가지의 타입 메서드로는 상속을 받았을 때,

  재정의가 불가능한 static 메서드와 재정의가 가능한 class 메서드가 있습니다.

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

클래스 사용

가변 인스턴스

- 클래스는 구조체와 다르게 var, let을 사용한 인스턴스 모두가 mutableProperty를 변경할 수 있습니다.

- 인스턴스를 할당할 때, var와 let에 관계없이 내부의 mutableProperty는 바꿔줄 수 있습니다.

var mutableReference: Sample = Sample()
mutableReference.mutableProperty = 200

let immutableReference: Sample = Sample()
immutableReference.mutableProperty = 200

 

불변 인스턴스

- 구조체와 동일하게 불변 인스턴스에 대한 값은 변경할 수 없습니다.

var mutableReference: Sample = Sample()
mutableReference.immutableProperty = 200

let immutableReference: Sample = Sample()
immutableReference.immutableProperty = 200

 

타입 프로퍼티

- 클래스에서 타입프로퍼티 사용은 구조체와 다름없습니다.

Sample.typeProperty = 300
Sample.typeMethod()

클래스 예제 2

- name, species라는 변수와 타입 메서드, 인스턴스 메서드를 가진 Zoo 클래스를 만들었습니다.

- 1번 코드를 보시면, Zoo라는 구조체가 타입 자체적으로 타입 메서드를 구현하여 "동물원입니다."가 출력됩니다.

- 2번 코드를 보시면, 인스턴스를 만든 후, introduce 인스턴스 메서드를 구현하여

  "저는 \(self.species) 동물 \(name)입니다." 코드가 출력됩니다.

- 3번 코드를 보시면, 불변 인스턴스인 let으로 선언했음에도 불구하고 내부의 name프로퍼티와 species 프로퍼티를 변경

   했음을 확인할 수 있습니다.

class Zoo {
    var name: String = "캥거루"
    var species: String = "포유류"

    static func introduce() {
        print("동물원입니다.")
    }
    
    func introduce() {
        print("저는 \(self.species) 동물 \(name)입니다.")
    }
}
// 1
Zoo.introduce()
// 2
var tiger: Zoo = Zoo()
tiger.name = "호랑이"
tiger.species = "고양이과"
tiger.introduce()
// 3
let kangaroo: Zoo = Zoo()
kangaroo.name = "코끼리"
kangaroo.species = "코끼리과"
kangaroo.introduce()

내용출처

https://www.youtube.com/watch?v=mV3wZ0tM_bk&list=PLz8NH7YHUj_ZmlgcSETF51Z9GSSU6Uioy&index=14 

 

'iOS > Swift 문법 심화 학습' 카테고리의 다른 글

오류 처리 [ error handling ]  (0) 2022.02.04
열거형 [ enum ]  (0) 2022.02.03
구조체 [ Struct ]  (0) 2022.02.03
클로저 고급  (0) 2022.02.02
클로저  (0) 2022.02.01

댓글