, yukarıdakilerden hiçbiri gerçekten Objective-C için herhangi bir bağlantısı vardır. Örneğiniz birkaç tane daha sorun içeriyor, ancak amaçlanan şekilde çalışmasını engelliyor.
MyObject
başlatıcıya sahip değil (Swift 2.2'den itibaren en az bir başlatıcı eklemelisiniz).
obj1
, obj2
, ... nedir? Sana örneklerini MyObject
Çeşidi olmak için bu amaçlayarak ediyoruz tahmin zaman, yöntem veya sınıf/yapılar türleri olarak bunlarla. (Eğer filter() {... }
den ()
atlayabilirsiniz unutmayın) amaçlandığı gibi yukarıdaki sabitleme Kodunuzla fiili filtreleme bölümü çalışacak olursa
örn: filtrelemeye alternatif olarak
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
doğrudan bir numaralandırma durumuna, numaranızın rawValue
türünü belirtebilir ve bunun yerine bununla eşleşebilirsiniz. Örneğin. Int
rawValue
kullanarak, numaranızdaki örneklerin aralıklarını (numaranızı rawValue
filtrelemeye ek olarak) gerçekleştirmenizi sağlar.
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
Eğer Xcode 7.3 kullanıyor musunuz? –