associatedtype:關(guān)聯(lián)類型,定義一個(gè)協(xié)議時(shí),有的時(shí)候聲明一個(gè)或多個(gè)關(guān)聯(lián)類型作為協(xié)議定義的一部分將會(huì)非常有用。關(guān)聯(lián)類型為協(xié)議中的某個(gè)類型提供了一個(gè)占位名(或者說別名),其代表的實(shí)際類型在協(xié)議被采納時(shí)才會(huì)被指定。你可以通過 associatedtype 關(guān)鍵字來指定關(guān)聯(lián)類型。
協(xié)議中不支持泛型,如果在協(xié)議中需要達(dá)到泛型這種類似的效果
我們可以使用 associatedtype 關(guān)鍵字。
//模型
class Animal {
var name: String?
var age : Int = 0
}
class Dog: Animal {
var color: String?
}
class Cat: Animal {
var action:String?
}
//定義一個(gè)協(xié)議
protocol AnimalProtocol {
//定義一個(gè)關(guān)聯(lián)類型
associatedtype T;
func append(_ item: T)
}
class Person: AnimalProtocol {
//在使用協(xié)議時(shí)需要明確指定協(xié)議中的關(guān)聯(lián)類型
typealias T = Dog;
func append(_ item: Dog) {
print("添加一只狗")
}
}
class Student: AnimalProtocol {
//在使用協(xié)議時(shí)需要明確指定協(xié)議中的關(guān)聯(lián)類型
typealias T = Cat
func append(_ item: Cat) {
print("添加一只貓")
}
}
其實(shí)我們還可以對協(xié)議中定義的 T(泛型)指定具體的類型,或則添加相應(yīng)的約束來限制類型:
protocol DogProtocol {
associatedtype T : Dog
func append(_ item: T)
}
協(xié)議類型作為返回值:
protocol TestProtocol {
associatedtype service
func creatService() -> service
}
protocol TestProtocol2 {
func creatService()
}
protocol TestProtocol3 {
func testMethod()
}
class TestClass2: TestProtocol2 {
func creatService() {
}
}
class TestClass3: TestProtocol3 {
func testMethod() {
}
}
class Test: TestProtocol {
typealias service = TestProtocol2
func creatService() -> service {
return TestClass2.init() // 協(xié)議作為返回值, 我們可以返回一個(gè)遵守該協(xié)議的實(shí)例對象
}
}
class Test1: TestProtocol {
typealias service = TestProtocol3
func creatService() -> service {
return TestClass3.init()// 協(xié)議作為返回值, 我們可以返回一個(gè)遵守該協(xié)議的實(shí)例對象
}
}