swift-associatedtype关键字 admin 2023-06-01 10:18:01 篇首语:本文由小编为大家整理,主要介绍了swift-associatedtype关键字相关的知识,希望对你有一定的参考价值。 Ns。JszhUOEr。CoM 协议中不支持该种方式的泛型,如果在协议中需要达到泛型这种类似的效果 我们可以使用associatedtype关键字 Ns。JszhUOEr。CoMassociatedtype:关联类型,定义一个协议时,有的时候声明一个或多个关联类型作为协议定义的一部分将会非常有用。关联类型为协议中的某个类型提供了一个占位名(或者说别名),其代表的实际类型在协议被采纳时才会被指定。你可以通过 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 //这里会报错 因为协议中对泛型有类型限制, 所以这里会报错 } Ns。JszhUOEr。CoM 如果上述协议中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关键字的主要内容,如果未能解决你的问题,请参考以下文章 C++格式化输出 uniapp关闭小程序就退出登录 您可能还会对下面的文章感兴趣: 相关文章 商丘私人空放联系方式_基本资料审核后快速就能放款平台 济宁私人借钱24小时在线,5万以上级别的贷款|无抵押个人借贷|秒下| 湖州空放私借2小时放款—身无分文借贷100%直接放款 宜昌纯私人放款微信电话——马上为您安排信贷服务+当日到账 蚌埠24小时私人放款联系方式随借随到-做生意借贷|应急周转|大额优先| 遵义空放借钱贷款联系电话:走投无路申请放款马上就到账 绵阳专业空放贷款私人联系方式,不看过往|先贷后放|马上拿钱| 德州附近个人放款电话号码多少:不审核+随借随还+当日成功+直接到账