简体   繁体   English

Swift 4:过滤数组

[英]Swift 4: Filtering Array

i am new to swift, currently practicing 我是新手,正在练习

here i have a plist file, which has an Array Of Dictionaries , each dictionary has one string, the plist has 3 records, it looks like this 这里我有一个plist文件, 其中有一个Array of Dictionaries ,每个字典有一个字符串,plist有3条记录,它看起来像这样

item 0:
kurdi: Googlee

item 1:
kurdi: Yahooe

item 2:
kurdi: Binge

here's a image for the plist; 这是plist的图片; Screenshot 11:52AM 截图11:52 AM

okay so the point is, when a user searches for oo for example two of the records contain oo , such as g oo gle and yah oo , i want to return an array of results, 好吧,关键是,当用户搜索oo ,例如其中两个记录包含oo ,例如g oo gle和yah oo ,我想返回结果数组,

for that case i used: 对于这种情况,我使用了:

let path = Bundle.main.path(forResource:"hello", ofType: "plist")
let plistData = NSArray(contentsOfFile: path!)
let objCArray = NSMutableArray(array: plistData!)

 if let swiftArray = objCArray as NSArray as? [String] {

     let matchingTerms = swiftArray.filter({
      $0.range(of: "oo", options: .caseInsensitive) != nil // here
        })
        print(matchingTerms)

    }

but unfortunately, when i print matchingTerms it returns nil .. thanks 但不幸的是,当我打印matchingTerms它返回nil ..谢谢

If you are new to Swift please learn first not to use NSMutable... Foundation collection types in Swift at all. 如果您不NSMutable... Swift,请先了解一下不要使用Swift中的NSMutable... Foundation集合类型。 (The type dance NSArray -> NSMutableArray -> NSArray -> Array is awful). (类型舞蹈 NSArray > NSMutableArray > NSArray > Array很糟糕)。 Use Swift native types. 使用Swift本机类型。 And instead of NSArray(contentsOfFile use PropertyListSerialization and the URL related API of Bundle . 而不是NSArray(contentsOfFile使用PropertyListSerializationBundleURL相关的API。

All exclamation marks are intended as the file is required to exist in the bundle and the structure is well-known. 所有感叹号均用于提供该文件包中所需的文件,并且其结构是众所周知的。

let url = Bundle.main.url(forResource:"hello", withExtension: "plist")!
let plistData = try! Data(contentsOf: url)
let swiftArray = try! PropertyListSerialization.propertyList(from: plistData, format: nil) as! [[String:String]]
let matchingTerms = swiftArray.filter({ $0["kurdi"]!.range(of: "oo", options: .caseInsensitive) != nil })
print(matchingTerms)

Cast swift array to [[String:Any]] not [String] . 将swift数组强制转换为[[String:Any]]而不是[String] And in filter you need to check the value of the key kurdi . 在过滤器中,您需要检查键kurdi的值。 Try this. 尝试这个。

if let swiftArray = objCArray as? [[String:Any]] {
    let matchingTerms = swiftArray.filter { (($0["kurdi"] as? String) ?? "").range(of: "oo", options: .caseInsensitive) != nil }
    print(matchingTerms)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM