프로토콜

Wongbing·2022년 1월 1일
0

Swift 는 프로토콜 지향언어이다. 프로토콜이란?

protocol CanFly {
    func fly()
    
}

class Bird {
    
    var isFemale = true
    
    func layEgg() {
        if isFemale {
            print("The bird makes a new bird in a shell")
        }
    }
}

class Eagle: Bird, CanFly{
    func fly() {
        print("The eagle flaps its wings and lifts of into the sky")
    }
    
    
    func soar() {
        print("The eagle glides in the air using air currents")
    }
    
}

class Penguin: Bird {
    func swim(){
        print("The panguin paddles through the water.")
    }
}

struct FlyingMuseum {//CanFly프로토콜을 가진 함수만 적용 가능하다 
    func flyingDemo(flyingObject: CanFly) {
        flyingObject.fly()
    }
}

struct Airplane: CanFly { //CanFly프로토콜 class, struct 둘다 적용가능
    func fly(){
        print("The airplane uses its engine to lift off into the air.")
    }
}

let myEagle = Eagle()
let myPenguin = Penguin()
let myPlane = Airplane()



let museum = FlyingMuseum()
museum.flyingDemo(flyingObject: myPlane)//myEagle가능 myPenguin불가능

class Myclass: SuperClass, firstProtocol, another Protocol {}
와 같은 방식으로 적용이 된다.

원래는 Bird클래스 안에 fly()가 있었지만, Bird클래스를 상속하는 Eagle, Penguin 클래스에서 Penguin은 날 수 없으므로 선택적으로 fly() 프로토콜을 Class에 적용 가능하도록 했다.
또한, Airplane는 원래 fly() 를 표현하기 위해 Bird클래스를 상속하는 class로 만들었지만, Bird클래스의 부수적인 fucn들 (layEgg) 까지도 상속이 되어 불필요한 func가 늘어나게 된다. 그리하여 struct에도 프로토콜이 적용 가능하다는 점을 이용해 class에서 struct로 바꾸어 프로토콜을 적용해주었다.

profile
IOS 앱개발 공부

0개의 댓글