Protocol에서 타입의 견본을 주는(placeholder) Generic 개념.
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 }
}
Int
형 thousand
을 가지는 NumberInt
struct는 다음과 같이 만들 수 있다.
struct NumberInt: NumberProtocol {
var thousand: Int {
return 1000
}
}
String
형 thousand
을 가지는 NumberString
struct는 다음과 같이 만들 수 있다.
struct NumberString: NumberProtocol {
var thousand: String {
return "1000"
}
}
associated type에는 제약도 설정해 줄 수 있다.
다음과 같이 associated type Number
에 Equatable
제약을 설정한다.
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"
}
}
하지만 커스텀으로 작성한 NotEquatable
class를 제약을 걸어둔 associated type Number
에 넣을 경우 Error을 띄우게 된다. NotEquatable
은 Equatable을 준수하고 있지 않기 때문이다.