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์ด์–ด์•ผ ํ•œ๋‹ค๋Š” ์ œ์•ฝ

Reference