如何在Swift中迭代CustomCollection泛型类型

时间:2015-09-05 17:43:26

标签: ios objective-c swift generics swift2

我有一个自定义集合类,其中包含用Obj-c编写的嵌入式数组。该类实现NSFastEnumerator协议,以便在Obj-c中进行迭代。

对于我的Swift类,我必须根据SOF上的apporaches添加以下代码。

extension CustomCollection: SequenceType {
    public func generate() -> NSFastGenerator {
        return NSFastGenerator(self)
    }
}

这又使它在Swift类中可迭代。

一切都很好,直到我需要在我的一个Swift基类中使用这个类作为Generic类型。

class SomeBaseClass<T: CustomCollection> {
    typealias Collection = T
    var model: Collection?
    // Implementation goes here
}

当我尝试迭代我的'model'属性时,我在构建期间收到命令信号失败错误。

知道如何做到这一点以及是否有可能做到这一点?

运行XCode 7 beta 6和Swift 2.0

感谢。

1 个答案:

答案 0 :(得分:0)

以下是我提出的Xcode 7.0.1:

首先是CustomCollection课程。我保持简单,因为我不知道你在做什么。

public class CustomCollection: NSFastEnumeration
{
    var array: NSMutableArray = []

    @objc public func countByEnumeratingWithState(state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int {
        var index = 0
        if state.memory.state != 0 {
            index = Int(state.memory.state)
        }
        if index >= self.array.count {
            return 0
        }
        var array = Array<AnyObject?>()
        while (index < self.array.count && array.count < len)
        {
            array.append(self.array[index++])
        }
        let cArray: UnsafeMutablePointer<AnyObject?> = UnsafeMutablePointer<AnyObject?>.alloc(array.count)
        cArray.initializeFrom(array)

        state.memory.state = UInt(index)
        state.memory.itemsPtr = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(cArray)
        return array.count
    }
}

然后是您提供的代码。

extension CustomCollection: SequenceType {
    public func generate() -> NSFastGenerator {
        return NSFastGenerator(self)
    }
}

class SomeBaseClass<T: CustomCollection>
{
    typealias Collection = T
    var model: Collection?
}

通过这一切,我能够运行以下

var myModel = CustomCollection()
myModel.array.addObject("This")
myModel.array.addObject("is")
myModel.array.addObject("a")
myModel.array.addObject(["complex", "test"])
var myVar = SomeBaseClass()
myVar.model = myModel

for myObject in myVar.model!
{
    print(myObject)
}

控制台打印

This
is
a
(
    complex,
    test
)

希望它有所帮助!

相关问题