Reputation:
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
item 0:
kurdi: Googlee
item 1:
kurdi: Yahooe
item 2:
kurdi: Binge
here's a image for the plist; Screenshot 11:52AM
okay so the point is, when a user searches for oo
for example two of the records contain oo
, such as goo
gle and yahoo
, i want to return an array of results,
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
Upvotes: 0
Views: 2291
Reputation: 285250
If you are new to Swift please learn first not to use NSMutable...
Foundation collection types in Swift at all. (The type dance NSArray
-> NSMutableArray
-> NSArray
-> Array
is awful). Use Swift native types. And instead of NSArray(contentsOfFile
use PropertyListSerialization
and the URL
related API of Bundle
.
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)
Upvotes: 2
Reputation: 19156
Cast swift array to [[String:Any]]
not [String]
. And in filter you need to check the value of the key 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)
}
Upvotes: 0