2015-09-05 25 views
3

我有一個自定義集合類,其中有一個嵌入數組,用Obj-c編寫。該類實現NSFastEnumerator協議以便在Obj-c中進行迭代。如何迭代Swift中CustomCollection泛型類型

對於我的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

謝謝。

+0

是否將'typealias Collection = CustomCollection'改爲'typealias Collection = T'修復了這個問題? – oisdk

+0

oisdk抱歉,這是一個錯誤。將更新問題。 – Peymankh

回答

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 
) 

希望它能幫助!