iOS面试集

Swift - 关键字associatedtype

2023-09-11  本文已影响0人  搬砖的crystal

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)
}

协议类型作为返回值:

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()// 协议作为返回值, 我们可以返回一个遵守该协议的实例对象
    }
}
上一篇 下一篇

猜你喜欢

热点阅读