Generic์ ๊ฒฝ์ฐ ์ฝ๋ ์ค๋ณต์ ์ค์ผ ์ ์๋ ์ข์ ๊ธฐ๋ฅ์ด๋ค. ์ ๋ค๋ค๋๋ค๋ฉด ์ค๊ธ(?) ์ด์์ ๊ฐ๋ฐ์๊ฐ ๋๋๋ฐ ํฐ ๋์์ ์ค ๊ฒ์ด๋ค. ๊ทธ๋ผ ์์ํด๋ณด์!
placeholder
<>
์์ ๋ค์ด๊ฐ ๊ฒ์ placeholder๋ผ ํจ- function๋ด๋ถ์์ parameter type์ด๋ return type์ผ๋ก ์ฌ์ฉ๊ฐ๋ฅ
func swap<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = a } struct Stack<Element> { var items = [Element]() mutating func push(_ item: Element) { self.items.append(item) } mutating func pop() -> Element { return self.items.removeLast() } }
Type Constraint
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
}
Associated Type
- protocol ์ ์ ์ ๊ทธ protocol์ด ์ฌ์ฉํ ์์์ type์ ์ ์ธํด ๋ ์ ์์
associatedtype
protocol Container { associatedtype Item // Item์ด๋ผ๋ type์ด ์์ ๊ฑฐ์ผ~ mutating func append(_ item: Item) var count: Int { get } subscript(i: Int) -> Item { get } } struct Stack<Element>: Container { var items = [Element]() mutating func push(_ item: Element) { self.items.append(item) } mutating func pop() -> Element { return self.items.removeLast() } typealias Item = Element // associated type์ธ Item์ Element๋ผ ํ ๊ฑฐ์ผ: type inference๋ก ์๋ต๊ฐ๋ฅ mutating func append(_ item: Element) { self.push(item) } var count: Int { return items.count } subscript(i: Int) -> Element { return items[i] } }
where
-
type parameter์ where์ ์ ์ด์ฉํด์ ์ ์ฝ ๊ฐ๋ฅ
func allItemsMatch<C1: Container, C2: Container>(_ c1: C1, c2: C2) -> Bool where C1.item == C2.Item, C1.Item: Equatable { }
C1.item == C2.Item
์ ๋ container์ item์ด ๋์ผํ type์ด๋ผ๋ ์ ์ฝC1.Item: Equatable
item์ด ๋น๊ต ๊ฐ๋ฅํ type์ด์ด์ผ ํ๋ค๋ ์ ์ฝ