首页 > 解决方案 > 通用协议属性声明

问题描述

假设我有一个关联类型 T 的协议

protocol Helper{
    associatedtype T
    func help(_ item: T)
}

在一个类中,我想声明一个属性

class Manager<T>{
    let item: T?
    let helper: Helper<T>
//Error: Cannot specialize non-generic type 'Helper'

    let anotherHelper: Helper 
//Error: Protocol 'Helper' can only be used as a generic constraint because it has Self or associated type requirements
}

如何声明和使用 helper 属性,使其强制符合 Helper 协议的类的类型?

我敢肯定,很多具有 Java/C# 或其他类似语言背景的人在尝试做类似的事情时都会遇到困难

标签: swift

解决方案


在这种特殊情况下,您T可以Manager<T>改为Helper

class Manager<T> where T : Helper {
    let item: T.T?
    let helper: T

    init(helper: T) {
        self.helper = helper
        item = nil
    }
}

如果你想要一个Helper<Int>,你做:

class IntHelper : Helper {
    typealias T = Int

     // ... 
}

然后使用Manager<IntHelper>.


推荐阅读