제네릭은 함수·타입·열거형·프로토콜 등에 타입 매개변수(type parameter)를 도입해, 여러 구체 타입에 대해 일관된 방식으로 동작하도록 만드는 기능이다.
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
struct Stack<Element> {
private var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
return items.popLast()
}
}
func findIndex<T: Equatable>(of value: T, in array: [T]) -> Int? {
for (i, element) in array.enumerated() where element == value {
return i
}
return nil
}
func compareItems<T: Equatable & Comparable>(_ a: T, _ b: T) -> Bool {
return a < b
}
func allItemsMatch<C1: Collection, C2: Collection>
(_ c1: C1, _ c2: C2) -> Bool
where C1.Element == C2.Element, C1.Element: Equatable {
guard c1.count == c2.count else { return false }
for (x, y) in zip(c1, c2) where x != y {
return false
}
return true
}
// 스택 예제
var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
print(intStack.pop() as Any) // Optional(2)
// 제약 조건 예제
let numbers = [3, 1, 4, 1]
if let idx = findIndex(of: 4, in: numbers) {
print("4의 인덱스:", idx) // 2
}
// where 절 예제
let a = [1, 2, 3]
let b = [1, 2, 3]
print(allItemsMatch(a, b)) // true