Swift filter array of strings

后端 未结 4 2097
日久生厌
日久生厌 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:31

    There is both a problem with GoZoner's answer for certain data types and also a slightly better way to do this. The following examples can show this:

    let animalArray: NSMutableArray = ["Dog","Cat","Otter","Deer","Rabbit"]
    let filteredAnimals = animalArray.filter { $0.rangeOfString("er") != nil }
    print("filteredAnimals:", filteredAnimals)
    
    filteredAnimals: [Dog, Cat, Otter, Deer, Rabbit]
    

    Likely not the set you expected!

    However this works fine this way if we don't type animalArray as an NSMutableArray:

    let animalArray = ["Dog","Cat","Otter","Deer","Rabbit"]
    let filteredAnimals = animalArray.filter { $0.rangeOfString("er") != nil }
    print("filteredAnimals:", filteredAnimals)
    
    filteredAnimals: [Otter, Deer]
    

    However I'd recommend using $0.contains() instead of $0.rangeOfString() != nil because it functions in both circumstances and slightly enhances the readability of the code:

    let animalArray: NSMutableArray = ["Dog","Cat","Otter","Deer","Rabbit"]
    let filteredAnimals = animalArray.filter { $0.contains("er") }
    print("filteredAnimals:", filteredAnimals)
    
    filteredAnimals: [Otter, Deer]
    

提交回复
热议问题