[SWIFT]Protocol extension

힐링힐링·2023년 11월 7일
0

SWIFT 문법

목록 보기
25/26

Protocol Extension

Protocol 을 정의할때는 내부 변수나 메서드 양식을 채택해야한다.
하지만, Protocol에서 추가로 Extension할경우
해당 Class 나 Struct 내부에서 그 값을 할당 안해도 되고, 외부에서 사용 가능한다

    /*
     프로토콜 예제 11
     Protocol 을 채택한 클래스, 구조체, 열거형에 공통된 기능을 추가하고 싶을 때, 어떤 방법을 사용해야 할까요?

     다음 예시 코드 결과가 출력되도록 코드를 추가해 보세요.
     */
protocol Animal11 {
    var name: String { get }
    func makeSound()
}

extension Animal11{
	//extension할 경우 굳이 채택한 구조 내부에 사용 안해도됨
    func introduce(){
        print("My name is \(name)")
    }
}
    // 예시 코드:
    class Dog: Animal11 {
        var name: String

        init(name: String) {
            self.name = name
        }

        func makeSound() {
            print("Woof!")
        }
    }

    struct Cat: Animal11 {
        var name: String

        func makeSound() {
            print("Meow!")
        }
    }

    enum Bird: Animal11 {
        case parrot(String)
        case sparrow(String)

        var name: String {
            switch self {
            case .parrot(let name):
                return name
            case .sparrow(let name):
                return name
            }
        }

        func makeSound() {
            switch self {
            case .parrot:
                print("Hello!")
            case .sparrow:
                print("Chirp!")
            }
        }
    }
profile
블로그 이전합니다 https://james-kim-tech.tistory.com/

0개의 댓글