Filter array of strings, including "like" condition

76,740

Solution 1

Use contains instead:

let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered)

Output

["Hello", "Halo"]

Thanks to @user3441734 for pointing out that functionality is of course only available when you import Foundation

Solution 2

In Swift 3.0

let terms = ["Hello","Bye","Halo"]

var filterdTerms = [String]()


func filterContentForSearchText(searchText: String) {
    filterdTerms = terms.filter { term in
        return term.lowercased().contains(searchText.lowercased())
    }
}


filterContentForSearchText(searchText: "Lo")
print(filterdTerms)

Output

["Hello", "Halo"]

Solution 3

Swift 3.1

let catalogNames = [ "Hats", "Coats", "Trousers" ]
let searchCatalogName = "Hats"

let filteredCatalogNames = catalogNames.filter { catalogName in 
    return catalogName.localizedCaseInsensitiveContains(searchCatalogName)
}

print(filteredCatalogNames)

Solution 4

my try...

let brands = ["Apple", "FB", "Google", "Microsoft", "Amazon"]

let b = brands.filter{(x) -> Bool in 
(x.lowercased().range(of: "A".lowercased()) != nil)
}
print(b) //["Apple", "Amazon"]

Solution 5

with help of String extension you can use pure Swift solution (without import Foundation). I didn't check the speed, but it shouldn't be worse as the foundation equivalent.

extension String {
    func contains(string: String)->Bool {
        guard !self.isEmpty else {
            return false
        }
        var s = self.characters.map{ $0 }
        let c = string.characters.map{ $0 }
        repeat {
            if s.startsWith(c){
                return true
            } else {
                s.removeFirst()
            }
        } while s.count > c.count - 1
        return false
    }
}

let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }

print(filtered) // ["Hello", "Halo"]

"a".contains("alphabet") // false
"alphabet".contains("")  // true
Share:
76,740
Roi Mulia
Author by

Roi Mulia

Updated on May 23, 2021

Comments

  • Roi Mulia
    Roi Mulia almost 3 years

    If my main array is ["Hello","Bye","Halo"], and I'm searching for "lo", it will filter the array only to ["Hello", "Halo"].

    This is what I've tried:

     let matchingTerms = filter(catalogNames) {
            $0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch) !=  nil
        }
    

    It throws

    Type of expression is ambiguous without more context
    

    Any suggestions?

  • user3441734
    user3441734 over 8 years
    .. and don't forget import Foundation
  • Roi Mulia
    Roi Mulia over 8 years
    Awesome, thanks. Give me couple min before i can upVote
  • luk2302
    luk2302 over 8 years
    @user3441734 thanks, you are right about that one - always forget the imports because they are already in the project.
  • GhostCat
    GhostCat about 7 years
    He asked for swift two syntax. What is the point of providing a swift3 answer?
  • Dilip Jangid
    Dilip Jangid about 7 years
    When some one search for filter string array only, he/she will get answer as well as may update knowledge of syntax in upgraded version
  • Hardik Darji
    Hardik Darji about 7 years
    how to add more than one condition in this ? e.g. let filtered = arr.filter { $0.containsString("lo") OR $0.containsString("ll") } Will work this ?
  • Resty
    Resty about 7 years
    I think it was asked for Swift 2, cose of it was actual at that moment, now we working with Swift 3 so it's more valuable for this moment.
  • Tommy K
    Tommy K almost 7 years
    @GhostCat because people like me come from Google looking for Swift 3 solutions :)
  • Er. Khatri
    Er. Khatri almost 7 years
    this is giving me error in playground Value of type 'String' ha no member 'contains'
  • Lucas Chwe
    Lucas Chwe about 5 years
    you need to plug in lowercased() for better results