[Udemy iOS & Swift Bootcamp] Protocol
*νλ‘ν μ½: μμ±μ΄λ λ©μλμ ννλ₯Ό 미리 λ§λ€μ΄λλ κ². μμμ μ’λ ꡬ쑰μ μΌλ‘ λ§λ€ μ μλλ‘.
μ΄ λ, νλ‘ν μ½μ μ μλ§ ν λΏ μΈλΆ λ΄μ©μ ꡬννμ§ μλλ€. κ»λ°κΈ°λ§ μλ€κ³ 보면 λ¨.
νλ‘ν μ½μ ν΄λμ€μ ꡬ쑰체μ μ μ©λ μ μλ€.
μμ μ½λ)
protocol CanFly{
func fly()
}
class Bird {
var isFemale = true
func layEgg(){
if isFemale {
print("The bird makes a new bird in a shell.")
}
}
}
class Egle: Bird, CanFly{
func fly() {
print("The elgle flpas its wings and lifts off into the sky.")
}
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: CanFly){
flyingObject.fly()
}
}
struct Airplan: CanFly {
func fly(){
print("The airplane uses its engine to lift off into the air.")
}
}
let myEgle = Egle()
myEgle.fly()
myEgle.layEgg()
myEgle.soar()
let myPenguin = Penguin()
myPenguin.layEgg()
myPenguin.swim()
let myPlane = Airplan()
myPlane.fly()
let museum = FlyingMuseum()
museum.flyingDemo(flyingObject: myPlane)
Bird ν΄λμ€μ fly() ν¨μλ₯Ό λ£μ΄λκ³ Egleκ³Ό Penguine, Airplaneμ΄ Bird ν΄λμ€λ₯Ό μμλ°μΌλ©΄ μ΄λ»κ² λ κΉ?
Egleμ Airplaneμ μλ λ μ μμ§λ§, Penguineμ΄ λ μ μλ μν©μ΄ μ°μΆλ κ²μ΄λ€. Oh No~~~
μ΄λ κ² μμ ꡬ쑰λ₯Ό μ’ λ 체κ³μ μΌλ‘ λ§λ€κ³ μΆμ λ Protocolμ μ¬μ©νλ©΄ λλ€.
CanFly νλ‘ν μ½μ λ§λ€κ³ CanFly νλ‘ν μ½μ΄ Fly() ν¨μλ₯Ό λ€κ³ μκ² ν λ€, Egleκ³Ό Airplaneμ΄ νλ‘ν μ½μ μ¬μ©νλ©΄ Penguineμ΄ λ μλ²λ¦¬λ μν©μ μ°μΆλμ§ μκ³ λͺ¨λ κ²μ΄ μμμ μΌλ‘ ꡬνλ κ²μ΄λ€.
* structμ μ μ©νκΈ°
struct MyStructure: FirstProtocol, AnotherProtocol{
//struct definition goes here
}
* classμ μ μ©νκΈ°
class MyClass: Superclass, FirstProtocol, AnotherProtocol{
//class definition goes here
}
Document μ°Έκ³
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols/
Documentation
docs.swift.org