【问题标题】:How to iterate over CustomCollection generic type in Swift如何在 Swift 中迭代 CustomCollection 泛型类型
【发布时间】:2015-09-05 17:43:26
【问题描述】:

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

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

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

这再次使它在 Swift 类中可迭代。

在我需要在我的一个 Swift 基类中将此类用作泛型类型之前,一切都很好。

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

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

知道这需要如何完成以及是否有可能完成?

运行 XCode 7 beta 6 和 Swift 2.0

谢谢。

【问题讨论】:

  • typealias Collection = CustomCollection 更改为typealias Collection = T 是否可以解决问题?
  • oisdk 对不起,这是一个错字。将更新问题。

标签: ios objective-c swift generics swift2


【解决方案1】:

这是我想出的 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
)

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2015-08-27
    相关资源
    最近更新 更多