我想创建一个可以存储符合某种协议(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/