使用协议对象进行纯粹快速设置

Jee*_*eef 19 protocols set swift

有没有办法让以下内容真正起作用?

V1 - "测试协议不符合Hashable"

protocol testProtocol  {
    //
}

class test {
    var s : Set<testProtocol>?
    init(){
    }
}
Run Code Online (Sandbox Code Playgroud)

V2 - "协议'testProtocol'只能用作通用约束,因为它具有Self或相关类型要求

protocol testProtocol : Hashable {
    //
}

class test {
    var s : Set<testProtocol>?
    init(){
    }
}
Run Code Online (Sandbox Code Playgroud)

我假设答案是否定的 - 因为协议(即使使用@objc标签)没有足够的信息?但也许我在这里缺少某种线条或东西.

Mar*_*n R 7

也许有更好的解决方案,但您可以使您的类通用:

protocol testProtocol : Hashable {
    //
}

class test<P: testProtocol> {
    var s : Set<P>?

    init() { }
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*ane 5

一种解决方案是将集合包装在类或结构中,并限制插入函数,使其仅接受符合协议可哈希的项。然后您可以使用SetofAnyHashable然后您可以在实现中

例如:

protocol MyProtocol {
    func doStuff()
}

class MyProtocolSet {
    var set = Set<AnyHashable>()

    func insert<T>(_ item: T) where T: MyProtocol, T: Hashable {
        set.insert(AnyHashable(item))
    }

    func iterate( doing: (MyProtocol) -> Void ) {
        for item in set {
            doing(item as! MyProtocol)
        }
    }
}

struct Foo: MyProtocol, Hashable {
    func doStuff() { print("foo") }
}

struct Bar: MyProtocol, Hashable {
    func doStuff() { print("bar") }
}

func test() {
    let set = MyProtocolSet()
    set.insert(Foo())
    set.insert(Bar())
    set.iterate { (item: MyProtocol) in
        item.doStuff()
    }
}
Run Code Online (Sandbox Code Playgroud)

通过对插入函数施加约束,您可以说“该集合必须包含符合协议且可散列的内容”,而实际上并未将协议限制为可散列。

如果包装集类本身可以是通用的,并接受要遵守的协议,那就更好了,但我还没有弄清楚这是否可能!