筛选自定义对象的数组

4

我有一个类,它不是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]

这导致了一个致命错误:array cannot be bridged from Objective-C

我应该如何适当地过滤数组?

我需要从NSObject进行子类化或使我的类符合任何协议吗?


你正在使用Xcode 7.3吗? - Pradeep K
1个回答

12
从您的问题中我的看法是,以上内容实际上与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”类型并与之匹配。例如,使用“Int”“rawValue”允许您执行模式匹配,比如说,对于枚举中的一系列情况进行筛选。(除了相对于“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

自定义类中是否需要init?let object1 = MyObject; object1.id = 1; object1.type = type1 ... 如何处理? - bluenowhere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接