흔히들 사용하는 OOP ( Object Oriented Programming ) 은
의도치 않게 모든 속성을 상속하게 되고, 이로 인한 복잡한 구조 때문에 시간이 지날수록 관리하기 어려워 짐
2015년 WWDC 에서 Swift 는 POP ( Protocol Oriented Programming ) 이라고 함
예시
기본적인 프로토콜 사용
protocol Vehicle {
let wheelCount: Int
func ride(with speed: Float)
}
class Bicycle: Vehicle {
let wheelCount = 2
func ride(with speed: Float) {
print("현재 속도는 \\(speed) 입니다")
}
}
class Car: Vehicle {
let wheelCount = 4
func ride(with speed: Float) {
print("현재 속도는 \\(speed) 입니다")
}
}
프로토콜 채택 시, 해당 프로토콜에 선언되어 있는 속성과 메소드는 모두 선언해주어야 함
하지만, 공통되는 속성이나 메소드의 경우, extension 으로 빼두어 미리 선언해두면, 이런 귀찮음을 해결할 수 있음
protocol Vehicle {
let wheelCount: Int
func ride(with speed: Float)
}
extension Vehicle {
func ride(with speed: Float) {
print("현재 속도는 \\(speed) 입니다")
}
}
class Bicycle: Vehicle {
let wheelCount = 2
}
class Car: Vehicle {
let wheelCount = 4
}
여러 개의 프로토콜도 채택 가능
protocol Wheel {
let count: Int
}
protocol Ride {
func setSpeed(to speed: Float)
}
class Bicycle: Wheel, Ride {
let count = 2
func setSpeed(to speed: Float) {
print("현재 속도는 \\(speed) 입니다")
}
}
사용하는 방법에 따라 아래와 같이도 가능
protocol Wheel {
var count: Int { get set }
}
protocol Ride {
func setSpeed(to speed: Float)
}
extension Ride {
func setSpeed(to speed: Float) {
print("현재 속도는 \\(speed) 입니다")
}
}
class Car: Wheel, Ride {}
class Bus: Wheel, Ride {}