将 NSMutableSet 和 NSMutableOrderedSet 桥接在一起的协议

Protocol bridging NSMutableSet and NSMutableOrderedSet together

Swift 3 中,我希望能够创建一个允许我添加元素并使用 for element in 进行迭代的协议。该协议应该适用于 NSMutableSetNSMutableOrderedSet(因为它们不继承自相同的 class)。

我知道 NSMutableSetNSMutableOrderedSet 不从同一个 class 继承是有充分理由的,它被解释为 here and here

但我想创建一个只使用 NSMutableSet(和 NSMutableOrderedSet)中所有方法的一小部分的协议。

我已经得到 add 的工作,像这样:

protocol MutableSet {
    func add(_ element: Any)
}

extension NSMutableSet: MutableSet {}
extension NSMutableOrderedSet: MutableSet {}

let one: NSString = "one"
let two: NSString = "two"

// Works if created with `NSMutableSet`
let mutableSet: MutableSet = NSMutableSet()

mutableSet.add(one)
mutableSet.add(two)

for element in mutableSet as! NSMutableSet {
    print(element)
}
/*
 This prints:
 one
 two
*/

// Also works if creating `NSMutableOrderedSet` instance
let mutableOrderedSet: MutableSet = NSMutableOrderedSet()
mutableOrderedSet.add(one)
mutableOrderedSet.add(two)
for element in mutableOrderedSet as! NSMutableOrderedSet {
    print(element)
}
/*
 This prints:
 one
 two
 */

但是我真的很想能够通过使用以下元素来迭代:

for element in mutableSet {
    print(element)
}

我正在尝试使 protocol MutableSet 符合 Sequence 协议,类似这样,但它不起作用:

protocol MutableSet: Sequence {
    func add(_ element: Any)
}

extension NSMutableSet: MutableSet {
    typealias Iterator = NSFastEnumerationIterator
    typealias Element = NSObject // I dont know what to write here
    typealias SubSequence = Slice<Set<NSObject>> // Neither here....
}

let one: NSString = "one"
let two: NSString = "two"

let mutableSet: MutableSet = NSMutableSet() // Compile Error: Protocol `MutableSet` can only be used as a generic constraint because it has Self or associated type requirements
mutableSet.add(one)
mutableSet.add(two)

for element in mutableSet { // Compile Error: Using `MutableSet` as a concrete type conforming to protocol `Sequence` is not supported
    print(element)
}

是否可以使我的协议符合 Sequence?我应该怎么做?我试过typealiasassociatedtypeElementIterator等各种组合。我也试过它对我不起作用。

编辑 2:在编辑 1 中回答我自己的问题

var count: Int { get } 使用此解决方案工作,但不确定它是否是最好的解决方案...如果不必在 [ 的扩展中实现 var elements: [Any] { get } 也很好=16=] 和 NSMutableOrderedSet, 但我想这是不可避免的?

protocol MutableSet: Sequence {
    subscript(position: Int) -> Any { get }
    func add(_ element: Any)
    var count: Int { get }
    var elements: [Any] { get }
}

extension MutableSet {
    subscript(position: Int) -> Any {
        return elements[position]
    }
}

extension NSMutableSet: MutableSet {
    var elements: [Any] {
        return allObjects
    }
}
extension NSMutableOrderedSet: MutableSet {
    var elements: [Any] {
        return array
    }
}

struct AnyMutableSet<Element>: MutableSet {
    private let _add: (Any) -> ()
    private let _makeIterator: () -> AnyIterator<Element>

    private var _getElements: () -> [Any]
    private var _getCount: () -> Int

    func add(_ element: Any) { _add(element) }
    func makeIterator() -> AnyIterator<Element> { return _makeIterator() }

    var count: Int { return _getCount() }
    var elements: [Any] { return _getElements() }

    init<MS: MutableSet>(_ ms: MS) where MS.Iterator.Element == Element {
        _add = ms.add
        _makeIterator = { AnyIterator(ms.makeIterator()) }
        _getElements = { ms.elements }
        _getCount = { ms.count }
    }
}

let one: NSString = "one"
let two: NSString = "two"

let mutableSet: AnyMutableSet<Any>
let someCondition = true
if someCondition {
    mutableSet = AnyMutableSet(NSMutableSet())
} else {
    mutableSet = AnyMutableSet(NSMutableOrderedSet())
}
mutableSet.add(one)
mutableSet.add(two)

for i in 0..<mutableSet.count {
    print("Element[\(i)] == \(mutableSet[i])")
}

// Prints:
// Element[0] == one
// Element[1] == two

编辑 1:跟进问题 使用@rob-napier 的出色答案和 type erasure 技术,我扩展了 protocol MutableSet 以具有 countsubscript 能力,但是我只能这样做使用丑陋的 func(名为 getCount),而不是 var。这是我正在使用的:

protocol MutableSet: Sequence {
    subscript(position: Int) -> Any { get }
    func getCount() -> Int
    func add(_ element: Any)
    func getElements() -> [Any]
}

extension MutableSet {
    subscript(position: Int) -> Any {
        return getElements()[position]
    }
}

extension NSMutableSet: MutableSet {
    func getCount() -> Int {
        return count
    }

    func getElements() -> [Any] {
        return allObjects
    }
}
extension NSMutableOrderedSet: MutableSet {
    func getElements() -> [Any] {
        return array
    }

    func getCount() -> Int {
        return count
    }
}

struct AnyMutableSet<Element>: MutableSet {
    private var _getCount: () -> Int
    private var _getElements: () -> [Any]
    private let _add: (Any) -> ()
    private let _makeIterator: () -> AnyIterator<Element>

    func getElements() -> [Any] { return _getElements() }
    func add(_ element: Any) { _add(element) }
    func makeIterator() -> AnyIterator<Element> { return _makeIterator() }
    func getCount() -> Int { return _getCount() }

    init<MS: MutableSet>(_ ms: MS) where MS.Iterator.Element == Element {
        _add = ms.add
        _makeIterator = { AnyIterator(ms.makeIterator()) }
        _getElements = ms.getElements
        _getCount = ms.getCount
    }
}

let one: NSString = "one"
let two: NSString = "two"

let mutableSet: AnyMutableSet<Any>
let someCondition = true
if someCondition {
    mutableSet = AnyMutableSet(NSMutableSet())
} else {
    mutableSet = AnyMutableSet(NSMutableOrderedSet())
}
mutableSet.add(one)
mutableSet.add(two)

for i in 0..<mutableSet.getCount() {
    print("Element[\(i)] == \(mutableSet[i])")
}
// Prints:
// Element[0] == one
// Element[1] == two

如何让它在协议中仅使用 var count: Int { get }var elements: [Any] 而不是函数?

几乎每个 "how do I with a PAT (protocol with associated type)..." 的答案都是 "put it in a box." 那个盒子是 type eraser。在你的情况下你想要一个 AnyMutableSet.

import Foundation

// Start with your protocol
protocol MutableSet: Sequence {
    func add(_ element: Any)
}

// Now say that NSMutableSet is one. There is no step two here. Everything can be inferred.
extension NSMutableSet: MutableSet {}

// Create a type eraser for MutableSet. Note that I've gone ahead and made it generic.
// You could lock it down to just Any, but why limit yourself
struct AnyMutableSet<Element>: MutableSet {
    private let _add: (Any) -> ()
    func add(_ element: Any) { _add(element) }
    private let _makeIterator: () -> AnyIterator<Element>
    func makeIterator() -> AnyIterator<Element> { return _makeIterator() }
    init<MS: MutableSet>(_ ms: MS) where MS.Iterator.Element == Element {
        _add = ms.add
        _makeIterator = { AnyIterator(ms.makeIterator()) }
    }
}

// Now we can use it
let one: NSString = "one"
let two: NSString = "two"

// Wrap it in an AnyMutableSet
let mutableSet = AnyMutableSet(NSMutableSet())
mutableSet.add(one)
mutableSet.add(two)

for element in mutableSet {
    print(element)
}

原则上还有另一种方法,即直接使用现有的“允许我添加元素并通过使用 for element in 进行迭代的协议。”这是两个协议:SetAlgebra & Sequence。在实践中,我发现让 NSMutableSetNSOrderedSet 符合 SetAlgebra 是......烦人的。 NSMutableSet基本在Swift 3. 接受Any在各个地方,但定义为超过AnyHashable。基本代码不起作用:

let s = NSMutableSet()
let t = NSMutableSet()
s.union(t)

但那是因为你不应该使用 NSMutableSet。它会自动桥接到 Set,您应该改用 Set。而且 Set 确实符合 SetAlgebra & Sequence 所以这很好。

但随后我们来到 NSOrderedSet。这很难过渡到 Swift(这就是基金会团队推迟这么久的原因)。在我看来,这真是一团糟,每次我尝试使用它时,我都会把它拔出来,因为它不能很好地与任何东西搭配。 (尝试使用 NSFetchedResultsController 来利用 "ordered relationship." 中的顺序)坦率地说,你最好的选择是将它包装在一个结构中并使该结构符合 SetAlgebra & Sequence

但是如果你不这样做(或者只是摆脱有序集,就像我最终总是这样做的那样),那么类型擦除几乎是你唯一的工具。