NSPredicate that ignores whitespaces

前端 未结 2 1417
不思量自难忘°
不思量自难忘° 2021-02-15 15:06

I need to use NSPredicate to match two strings, case-insensitive, diacritic insensitive, and whitespace-insensitive.

The predicate would look something

2条回答
  •  清酒与你
    2021-02-15 15:34

    Swift 4:

    func ignoreWhiteSpacesPredicate(id: String) -> NSPredicate {
        return NSPredicate(block: { (evel, binding) -> Bool in
            guard let str = evel as? String else {return false}
            let strippedString = str.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
            let strippedKey = id.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
            return strippedString.caseInsensitiveCompare(strippedKey) == ComparisonResult.orderedSame
        })
    }
    

    Example:

    let testArray:NSArray =  ["abc", "a bc", "A B C", "AB", "a B d", "A     bC"]
    let filteredArray = testArray.filtered(using: ignoreWhiteSpacesPredicate(id: "a B C")) 
    

    Result:

    ["abc", "a bc", "A B C", "A bC"]

提交回复
热议问题