Swift filter array of strings

后端 未结 4 1984
日久生厌
日久生厌 2021-02-20 15:49

I\'ve had troubles filtering array of keywords (strings) in swift ,My code:

self.filteredKeywords=filter(keywords.allValues, {(keyword:NSString) ->                    


        
4条回答
  •  春和景丽
    2021-02-20 16:26

    Your filter is over [AnyObject], but your closure takes NSString. These need to match. Also, your result needs to be a Bool, not a Bool?. You can address these simply like this:

    self.filteredKeywords = filter(keywords.allValues, {
        let keyword = $0 as? NSString
        return keyword?.containsString(searchText) ?? false
    })
    

    This accepts AnyObject and then tries to coerce it down to NSString. It then nil-coalleces (??) the result to make sure it always is a Bool.

    I'd recommend, though, treating keywords as a [String:String] rather than an NSDictionary. That would get rid of all the complications of AnyObject. Then you can just do this:

    self.filteredKeywords = keywords.values.filter { $0.rangeOfString(searchText) != nil }
    

    Whenever possible, convert Foundation collections into Swift collections as soon as you can and store those. If you have incoming Foundation objects, you can generally convert them easily with techniques like:

    let dict = nsdict as? [String:String] ?? [:]
    

    Or you can do the following to convert them such that they'll crash in debug (but silently "work" in release):

    func failWith(msg: String, value: T) -> T {
        assertionFailure(msg)
        return value
    }
    
    let dict = nsdict as? [String:String] ?? failWith("Couldn't convert \(d)", [:])
    

提交回复
热议问题