首页 > 解决方案 > 协议关联类型和 <>

问题描述

在 swift 协议中使用带有函数的泛型或使用 associatedType 有什么区别?

protocol Repository {
    associatedtype T
    func add(data : T) -> Bool
}

protocol Repository {
    func add<T>(data : T) -> Bool
}

标签: swiftgenericsprotocols

解决方案


定义的关联类型使符合协议的类成为强类型。这提供了编译时错误处理。

另一方面,泛型类型使符合协议的类更加灵活。

例如:

protocol AssociatedRepository {
    associatedtype T
    func add(data : T) -> Bool
}

protocol GenericRepository {
    func add<T>(data : T) -> Bool
}


class A: GenericRepository {
    func add<T>(data : T) -> Bool {
        return true
    }
}

class B: AssociatedRepository {
    typealias T = UIViewController
    func add(data : T) -> Bool {
        return true
    }
}

classA可以将任何类放入add(data:)函数中,因此您需要确保该函数处理所有情况。

A().add(data: UIView())
A().add(data: UIViewController())

两者都是有效的

但是对于类B,当您尝试放置除UIViewController

B().add(data: UIView()) // compile-time error here
B().add(data: UIViewController())

推荐阅读