Swift 프로토콜(Protocol)은 메서드, 속성, 기타 요구사항의 청사진을 정의한다. 프로토콜 지향 프로그래밍(POP)의 핵심으로, 클래스보다 프로토콜 조합을 권장한다.
프로토콜 기본
swift
protocol Greetable {
var name: String { get }
func greet() -> String
}
struct Person: Greetable {
let name: String
func greet() -> String { "안녕하세요, (name)입니다!" }
}
// 프로토콜 타입으로 사용
var g: Greetable = Person(name: "Alice")
print(g.greet())
프로토콜 확장 (Protocol Extension)
swift
protocol Describable {
var description: String { get }
}
// 기본 구현 제공
extension Describable {
func printDescription() {
print("설명: (description)")
}
}
// 타입 제약 확장
extension Collection where Element: Comparable {
func sortedAndFiltered(above threshold: Element) -> [Element] {
return self.filter { $0 > threshold }.sorted()
}
}
Codable (Encodable + Decodable)
swift
struct Article: Codable {
let id: Int
let title: String
let published: Bool
let tags: [String]
}
// JSON 인코딩
let article = Article(id: 1, title: "Swift", published: true, tags: ["ios"])
let data = try JSONEncoder().encode(article)
// JSON 디코딩
let decoded = try JSONDecoder().decode(Article.self, from: data)
print(decoded.title) // Swift
연관 타입 (Associated Types)
swift
protocol Container {
associatedtype Item
var count: Int { get }
mutating func append(_ item: Item)
subscript(i: Int) -> Item { get }
}
struct Stack<Element>: Container {
private var items: [Element] = []
var count: Int { items.count }
mutating func append(_ item: Element) { items.append(item) }
subscript(i: Int) -> Element { items[i] }
}
관련 개념