πŸ“± App Development Study/iOS🍎

[Udemy iOS & Swift Bootcamp] Protocol

ibelieveinme 2023. 4. 10. 02:20
728x90

*ν”„λ‘œν† μ½œ: μ†μ„±μ΄λ‚˜ λ©”μ†Œλ“œμ˜ ν˜•νƒœλ₯Ό 미리 λ§Œλ“€μ–΄λ†“λŠ” 것. 상속을 쒀더 ꡬ쑰적으둜 λ§Œλ“€ 수 μžˆλ„λ‘.

이 λ•Œ, ν”„λ‘œν† μ½œμ€ μ •μ˜λ§Œ ν•  뿐 μ„ΈλΆ€ λ‚΄μš©μ€ κ΅¬ν˜„ν•˜μ§€ μ•ŠλŠ”λ‹€. 껍데기만 μžˆλ‹€κ³  보면 됨.

ν”„λ‘œν† μ½œμ€ ν΄λž˜μŠ€μ™€ ꡬ쑰체에 적용될 수 μžˆλ‹€.

 

μ˜ˆμ‹œ μ½”λ“œ)

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

 

728x90