본문 바로가기
Smart Device/Swift

Swift Generics

by 언덕너머에 2014. 7. 3.

- Generics

generic 함수나 type을 만들기 위해 함수명이나 타입명 뒤에 '<>'를 넣고 그 안에 명을 쓰면된다.

func repeat<T>(item: T, times: Int) -> [T] {

    var result = [T]()

    for i in 0...times {

        result.append(item)

    }

    return result

}

repeat("knock", 4)

-> ["knock", "knock", "knock", "knock", "knock"]


classes, enumerations 그리고 structures 뿐만 아니라 함수나 매서드까지 제네릭형식으로 만들 수 있다.

// Reimplement the Swift standard library's optional type

enum OptionalValue<T> {

    case None

    case Some(T)

}

var possibleInteger: OptionalValue<Int> = .None

possibleInteger = .Some(100)


protocol을 구현하기 위한 type을 요청하거나 동일한 두 타입을 요청하거나,

특별한 슈퍼클래스를 가지는 클래스를 요청하는 리스트를 지정하기 위해 

타입명 뒤에 키워드 'where'를 사용할 수 있다.

func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {

    for lhsItem in lhs {

        for rhsItem in rhs {

            if lhsItem == rhsItem {

                return true

            }

        }

    }

    return false

}

anyCommonElements([1, 2, 3], [3])


구문이 간단하다면 키워드 'where'를 생략하고 ':' 뒤에 protocol 또는 class name을

작성하면 된다. '<T: Equatable>은 <T where T: Equtable>와 동일하다.