2016-03-28 101 views
0

我有一個類,它不是NSObject的子類和該類的實例數組。過濾自定義對象數組

enum ObjectType{ 
    case type1 
    case type2 
    case type3 
} 

class MyObject { 
    var type = ObjectType! 
    //some other properties... 
} 

let array = [obj1(type:type1), 
      obj2(type:type2), 
      obj3(type:type3), 
      obj4(type:type2), 
      obj5(type:type3)] 

let type2Array = array.filter(){ $0.type == .type2} 
// type2Array is supposed to be [obj2, obj4] 

這是造成fatal error: array cannot be bridged from Objective-C

我怎麼能適當濾波器陣列?

我是否必須從NSObject繼承子類或使我的類符合任何協議?

+0

您使用的是Xcode 7.3嗎? –

回答

3

從我的問題中可以看出,以上都沒有與Objective-C有任何關聯。但是,您的示例包含一些其他問題,使其無法按預期工作。

  • MyObject沒有初始值設定項(從Swift 2.2開始,至少應包含一個初始值設定項)。
  • 什麼是obj1,obj2,...?您將這些視爲方法或類別/結構類型,當我推測您打算將這些設爲實例MyObject類型。

如果固定上面,你的代碼的實際濾波部分按預期(請注意,你可以省略從filter() {... }()),將工作如:

enum ObjectType{ 
    case type1 
    case type2 
    case type3 
} 

class MyObject { 
    var type : ObjectType 
    let id: Int 
    init(type: ObjectType, id: Int) { 
     self.type = type 
     self.id = id 
    } 
} 

let array = [MyObject(type: .type1, id: 1), 
      MyObject(type: .type2, id: 2), 
      MyObject(type: .type3, id: 3), 
      MyObject(type: .type2, id: 4), 
      MyObject(type: .type3, id: 5)] 

let type2Array = array.filter { $0.type == .type2} 
type2Array.forEach { print($0.id) } // 2, 4 

作爲替代過濾直接枚舉的情況下,您可以指定枚舉的rawValue類型並與其匹配。例如。使用IntrawValue可讓您(除了篩選w.r.t.t.t.t.t. rawValue)對枚舉中的案例範圍進行模式匹配。

enum ObjectType : Int { 
    case type1 = 1 // rawValue = 1 
    case type2  // rawValue = 2, implicitly 
    case type3  // ... 
} 

class MyObject { 
    var type : ObjectType 
    let id: Int 
    init(type: ObjectType, id: Int) { 
     self.type = type 
     self.id = id 
    } 
} 

let array = [MyObject(type: .type1, id: 1), 
      MyObject(type: .type2, id: 2), 
      MyObject(type: .type3, id: 3), 
      MyObject(type: .type2, id: 4), 
      MyObject(type: .type3, id: 5)] 

/* filter w.r.t. to rawValue */ 
let type2Array = array.filter { $0.type.rawValue == 2} 
type2Array.forEach { print($0.id) } // 2, 4 

/* filter using pattern matching, for rawValues in range [1,2], 
    <=> filter true for cases .type1 and .type2 */ 
let type1or2Array = array.filter { 1...2 ~= $0.type.rawValue } 
type1or2Array.forEach { print($0.id) } // 1, 2, 4 
+0

是否需要在自定義類中有init?怎麼樣'let object1 = MyObject; object1.id = 1; object1.type = type1 ...'? – bluenowhere