프로토콜이란?

Woozoo·2022년 12월 17일
0
protocl MyProtocol {
	//Define Protocol
}
class Bird {
	
	var isFemale = true

	func layEgg() {
    	if isFemale {
        	print("The bird makes a new bird in a shell.")
        }
    }
    
	func fly() {
    	print("The bird flaps its wings and lifts off into the sky.")
    }
}    

class Eagle: Bird {
	func soar() {
    	print("The eagle glides in the air using air currents.")
    }
}

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

struct FlyingMuseum {
	func flyingDemo(flyingObject: Bird) {
    	flyingObject.fly()
    }
}

class Airplane: Bird {

}

let myEagle = Eagle()
myEagle.fly()
myEagle.layEgg()
myEagle.soar()

let myPenguin = Penguin()
myPenguin.layEgg()
myPenguin.swim()
myPenguin.fly() // ???

let museum.flyingDemo(flyingObject: myEagle)

위와 같이 코드를 점점 확장시켜나가다 보면 상속에 있어서 이상한 경우가 생긴다.
이럴 때 프로토콜을 채택해서 보다 명확하게 코드를 정리한다.

protocol CanFly {
	func fly()
}

함수 구현부는 없음!

위의 코드를 수정해본다면
Bird 클래스의 fly 메소드를 없애고
방금 작성한 CanFly 프로토콜을 채택해주는 방법으로 수정해 볼 수 있겠다.
(프로토콜을 채택하면 구현부 작성해줘야함)

그리고 class로 선언했던 Airplane도 struct로 바꾸고 프로토콜 채택하면 됨.

또!!!

FlyingMuseum 메소드 flyingDemo에 들어가는 프로퍼티의 데이터 타입을
프.로.토.콜! 로도 작성이 가능함!!!

profile
우주형

0개의 댓글

관련 채용 정보