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:Equatable
associatedtype 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()// 协议作为返回值, 我们可以返回一个遵守该协议的实例对象
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值