๐Ÿ“ฑ 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