Programming/Swift

swift 구조체에서 protocol 사용 예제 1

알레아 2022. 8. 15. 23:37
반응형

struct에서 공통된 기능을 쓰기 위해서 protocol을 통해 추상화 과정을 거친다.

하지만 일부 기능은 구현이 필요 없는 경우도 존재한다.

protocol Car {
    func stop() {
    
    }
    
    func autostop() {
    
    }
}

struct Truck: Car {
    func stop() {
    
    }
    
    func autostop() {
    
    }
}

struct Van: Car {
    func stop() {
    
    }
    
    func autostop() {
    
    }
}

 

일부 추상화 함수를 extension을 통해 작성하게 되면, 해당 프로토콜을 채택한 struct에서 모두 구현해야할 필요가 없어지게 된다.

protocol Car {
    func stop() {
    
    }
}

extension Car {
    func autostop() {
    
    }
}

struct Truck: Car {
    func stop() {
    
    }
    
    func autostop() {
    
    }
}

struct Van: Car {
    func stop() {
    
    }
}

 

참고 문서

http://blog.whatifill.com/blog/swift-protocol-programming

반응형