본문 바로가기
Swift

Swift: 객체지향 프로그래밍의 요소 예제

by songmoro 2024. 8. 12.
728x90

클래스(Class), 메소드(Method), 프로퍼티(Property), 인스턴스(Instance)

class Chicken { // Class
    var weight: Double = 3.5 // Property
    
    func produce() { // Method
        print("produce egg!!")
    }
}

class Cow { // Class
    var weight: Double = 300.0 // Property
    
    func produce() { // Method
        print("produce milk!!")
    }
}

let chicken = Chicken() // Instance
let cow = Cow() // Instace

 

추상화(Abstraction), 상속(Inheritance)

class Animal {
    var weight: Double // Abstraction
    init(_ weight: Double)
    
    func produce() { // Abstraction
        print("can't produce anything")
    }
}

class Chicken: Animal { ... } // Inheritance
class Cow: Animal { ... } // Inheritance

 

다형성(Polymorphism)

class Animal { ... }

class Chicken: Animal {
    override func produce() { // overriding
        print("produce egg!!")
    }
    
    func produce(count: Int) { // overloading
        print("produce \\(count) egg!!")
    }
}

class Cow: Animal {
    override func produce() { // overriding
        print("produce milk!!")
    }
}

 

캡슐화(Encapsulation)

class Animal {
    private var weight: Double // Encapsulation
    init(_ weight: Double) { self.weight = weight }
    ...
}

class Chicken: Animal { ... }
class Cow: Animal { ... }

let cow = Cow(300.0)
cow.weight = -150 // 'weight' is inaccessible due to 'private' protection level
728x90

'Swift' 카테고리의 다른 글

Swift: XCTest  (0) 2024.08.12
Swift: 정규 표현식  (0) 2024.08.12
노션 API w/ SwiftUI  (1) 2024.05.01
Swift: Dictionary  (0) 2023.12.12
Swift: Combine(4) - 실전압축콤바인예제  (0) 2023.11.03