Associated Type

Minseok, Kim·2021년 7월 10일
0

요약

Protocol에서 타입의 견본을 주는(placeholder) Generic 개념.

기본 개념

PlaceHolder 역할

An associated type gives a placeholder name to a type that’s used as part of the protocol.
associated type은 protocol에 사용되는 타입의 견본(placeholder name)을 주는 역할을 한다.

Generic에 포함된 개념이다.
한 마디로 protocol을 작성할 때 각각의 property에 적용하는 Generic Type이라고 생각할 수 있다.

예시

다음과 같은 NumberProtocol이라는 protocol이 있다고 가정하자. 그 안의 thousand property는 1,000의 자리 숫자를 가진다. 그 값은 Int형 일 수도 있고 String형 일 수도 있다. 이를 해결하기 위해서 associated type Number을 설정한다.

protocol NumberProtocol {
    associatedtype Number
    var thousand: Number { get }
}

Intthousand을 가지는 NumberInt struct는 다음과 같이 만들 수 있다.

struct NumberInt: NumberProtocol {
    var thousand: Int {
        return 1000
    }
}

Stringthousand을 가지는 NumberString struct는 다음과 같이 만들 수 있다.

struct NumberString: NumberProtocol {
    var thousand: String {
        return "1000"
    }
}

제약 설정

associated type에는 제약도 설정해 줄 수 있다.

예시

다음과 같이 associated type NumberEquatable 제약을 설정한다.

protocol NumberProtocol {
    associatedtype Number: Equatable
    var thousand: Number { get }
}

위에서 작성한 Int형과 String형을 가지는 Struct들은 오류가 발생하지 않는다. 기본적으로 Swift의 Int형과 String형 모두 Equatable을 준수하기 때문이다.

struct NumberInt: NumberProtocol {
    var thousand: Int {
        return 1000
    }
}

struct NumberString: NumberProtocol {
    var thousand: String {
        return "1000"
    }
}

하지만 커스텀으로 작성한 NotEquatableclass를 제약을 걸어둔 associated type Number에 넣을 경우 Error을 띄우게 된다. NotEquatable은 Equatable을 준수하고 있지 않기 때문이다.

참고자료

profile
iOS, Swift Dev

0개의 댓글