篇首语:本文由小编为大家整理,主要介绍了swift-associatedtype关键字相关的知识,希望对你有一定的参考价值。
协议中不支持该种方式的泛型,如果在协议中需要达到泛型这种类似的效果
我们可以使用associatedtype
关键字
associatedtype
:关联类型,定义一个协议时,有的时候声明一个或多个关联类型作为协议定义的一部分将会非常有用。关联类型为协议中的某个类型提供了一个占位名(或者说别名),其代表的实际类型在协议被采纳时才会被指定。你可以通过 associatedtype 关键字来指定关联类型。
示例代码(在使用协议时指定关联类型的具体类型):
//模型class Animal { var name: String? var age : Int = 0}class Dog: Animal { var color: String?}class Cat: Animal { var action:String?}//定义一个协议protocol AnimalProtocol { //定义一个关联类型 associatedtype T; func append(_ item: T)}class Person: AnimalProtocol { //在使用协议时需要明确指定协议中的关联类型 typealias T = Dog; func append(_ item: Dog) { print("添加一只狗") } }class Student: AnimalProtocol { //在使用协议时需要明确指定协议中的关联类型 typealias T = Cat func append(_ item: Cat) { print("添加一只猫") }}
其实我们还可以对协议中定义的T(泛型)指定具体的类型,或则添加相应的约束来限制类型
protocol DogProtocol { associatedtype T : Dog func append(_ item: T)}class Dog2: DogProtocol { typealias T = Cat //这里会报错 因为协议中对泛型有类型限制, 所以这里会报错 }
如果上述协议中T的类型置顶成为Animal
类型的话就不会报错了
protocol DogProtocol { associatedtype T : Animal func append(_ item: T)}class Dog2: DogProtocol { typealias T = Cat func append(_ item: Cat) { } }
添加相应的规则示例:
associatedtype Item:Equatableassociatedtype Suffix: SuffixableContainer where Suffix.Item == ItemType
协议类型作为返回值:
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() // 协议作为返回值, 我们可以返回一个遵守该协议的实例对象 }}class Test1: TestProtocol { typealias service = TestProtocol3 func creatService() -> service { return TestClass3.init()// 协议作为返回值, 我们可以返回一个遵守该协议的实例对象 }}
以上是关于swift-associatedtype关键字的主要内容,如果未能解决你的问题,请参考以下文章