[Swift 정면돌파] 05. 구조체와 클래스

H43RO·2021년 8월 1일
1

Swift 정면돌파

목록 보기
5/19
post-thumbnail

본 시리즈는 아래 강의자료를 기반으로 작성되었습니다.
https://www.boostcourse.org/mo122/joinLectures/38564

오늘은 구조체, 클래스에 대해 공부해보았다. 스위프트는 구조체의 활용성이 매우 뛰어난 언어임을 알게 되었다.

구조체 개념

→ 스위프트 대부분 타입은 구조체로 이루어져있음
→ 구조체는 값 (Value) 타입임

구조체 프로퍼티 및 메소드 구현

struct Sample {
    // 가변 프로퍼티(값 변경 가능)
    var mutableProperty: Int = 100 
    
    // 불변 프로퍼티(값 변경 불가능)
    let immutableProperty: Int = 100 
    
    // 타입 프로퍼티(static 키워드 -> 타입 자체가 사용하는 프로퍼티)
    static var typeProperty: Int = 100 
    
    // 인스턴스 메서드(생성된 인스턴스 각각이 사용하는 메서드)
    func instanceMethod() {
        print("instance method")
    }
    
    // 타입 메서드(static 키워드 사용 : 타입 자체가 사용하는 메서드)
    static func typeMethod() {
        print("type method")
    }
}

구조체 사용

// 가변 인스턴스 생성
var mutable: Sample = Sample()

mutable.mutableProperty = 200

// 불변 프로퍼티는 인스턴스 생성 후 수정할 수 없음
// 컴파일 오류 발생
// mutable.immutableProperty = 200

// 불변 인스턴스
let immutable: Sample = Sample()

// 불변 인스턴스는 아무리 가변 프로퍼티라도
// 인스턴스 생성 후에 수정할 수 없음
// immutable.mutableProperty = 200
// immutable.immutableProperty = 200

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

// 생성된 인스턴스는 타입 프로퍼티나 타입 메서드를 사용 못함
// mutable.typeProperty = 400
// mutable.typeMethod()

구조체 예시

struct Student {
	// 가변 프로퍼티
    var name: String = "unknown"

    // 기본 키워드도 `로 묶어주면 이름으로 사용할 수 있음 (굳이..)
    var `class`: String = "Swift"
    
    // 타입 메서드
    static func selfIntroduce() {
        print("학생타입입니다")
    }
    
    // 인스턴스 메서드
    func selfIntroduce() {
        print("저는 \(self.class)\(name)입니다")
    }
}

// 타입 메서드 사용
Student.selfIntroduce() // 학생타입입니다

// 가변 인스턴스 생성
var yagom: Student = Student()
yagom.name = "H43RO"
yagom.class = "스위프트"
yagom.selfIntroduce()   // 저는 스위프트반 H43RO입니다

// 불변 인스턴스 생성
let lulu: Student = Student()

// 불변 인스턴스이므로 프로퍼티 값 변경 불가
// lulu.name = "LULU"
lulu.selfIntroduce() // 저는 Swift반 unknown입니다

클래스 개념

→ 클래스는 참조 (Reference) 타입
→ 다중 상속 X

클래스 프로퍼티 및 메소드 구현

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 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()

클래스 예시

class Student {
	// 가변 프로퍼티
    var name: String = "unknown"
    var `class`: String = "Swift"
    
    // 타입 메서드
    class func selfIntroduce() {
        print("학생타입입니다")
    }
    
    // 인스턴스 메서드
    func selfIntroduce() {
        print("저는 \(self.class)\(name)입니다")
    }
}

// 타입 메서드 사용
Student.selfIntroduce() // 학생타입입니다

// 인스턴스 생성
var yagom: Student = Student()
yagom.name = "H43RO"
yagom.class = "스위프트"
yagom.selfIntroduce()   // 저는 스위프트반 H43RO입니다

// 인스턴스 생성
let lulu: Student = Student()
lulu.name = "루루"
lulu.selfIntroduce() // 저는 Swift반 루루입니다
profile
어려울수록 기본에 미치고 열광하라

0개의 댓글