ios - 在 swift 中使用协议(protocol)作为数组类型和函数参数

标签 ios swift generics swift-protocols

我想创建一个可以存储符合某种协议(protocol)的对象的类。对象应存储在类型化数组中。根据 Swift 文档,协议(protocol)可以用作类型:

Because it is a type, you can use a protocol in many places where other types are allowed, including:

  • As a parameter type or return type in a function, method, or initializer
  • As the type of a constant, variable, or property
  • As the type of items in an array, dictionary, or other container

但是以下会产生编译器错误:

Protocol 'SomeProtocol' can only be used as a generic constraint because it has Self or associated type requirements

你应该如何解决这个问题:

protocol SomeProtocol: Equatable {
    func bla()
}

class SomeClass {
    
    var protocols = [SomeProtocol]()
    
    func addElement(element: SomeProtocol) {
        self.protocols.append(element)
    }
    
    func removeElement(element: SomeProtocol) {
        if let index = find(self.protocols, element) {
            self.protocols.removeAtIndex(index)
        }
    }
}

最佳答案

您遇到了 Swift 协议(protocol)问题的一个变体,目前还没有好的解决方案。

另见 Extending Array to check if it is sorted in Swift? ,它包含有关如何解决它的建议,这些建议可能适合您的特定问题(您的问题非常笼统,也许您可​​以使用这些答案找到解决方法)。

关于ios - 在 swift 中使用协议(protocol)作为数组类型和函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24888560/

相关文章:

ios - 计算器中的历史(Swift)

swift - Swift 中的链接方法

swift - 快速保存和检索解析中的图像

c# - 当类型参数为 IEnumerable<T> 时,如何将扩展方法附加到泛型类?

ios - Swift 单元测试无法识别新的类初始值设定项

ios遍历NSDictionary

ios - 如何最好地确保在触发完成处理程序之前我拥有所有数据?

iphone - 图像未在 iOS 3.2 上显示

C# 将 List<int> 转换为 List<double>

reactjs - 以类型作为参数的通用 TypeScript API