protocol Speakable {
func speak()
}
struct Person: Speakable {
func speak() {
print("안녕하세요!")
}
}
let person = Person()
person.speak() // 출력: 안녕하세요!
프로토콜은 다음을 요구할 수 있습니다:
protocol Identifiable {
var id: String { get }
}
protocol Movable {
func move(to point: Int)
}
protocol Creatable {
init(name: String)
}
protocol Container {
associatedtype Item
func add(_ item: Item)
}
where 절로 특정 조건을 만족하는 타입에만 확장 적용 가능.protocol Printable {
func printValue()
}
extension Printable {
func printValue() {
print("기본 출력")
}
}
struct Number: Printable {}
let num = Number()
num.printValue() // 출력: 기본 출력
protocol Eatable {
func eat()
}
protocol Flyable {
func fly()
}
struct Bird: Eatable, Flyable {
func eat() { print("먹는다") }
func fly() { print("난다") }
}