从您的问题中我的看法是,以上内容实际上与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) }
作为一种直接筛选到枚举情况的另一种选择,您可以指定枚举的“rawValue”类型并与之匹配。例如,使用“Int”“rawValue”允许您执行模式匹配,比如说,对于枚举中的一系列情况进行筛选。(除了相对于“rawValue”的筛选)。
enum ObjectType : Int {
case type1 = 1
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.rawValue == 2}
type2Array.forEach { print($0.id) }
let type1or2Array = array.filter { 1...2 ~= $0.type.rawValue }
type1or2Array.forEach { print($0.id) }