Swift过滤字符串数组

时间:2015-04-04 15:29:48

标签: ios arrays string swift filtering

我在swift中过滤了一系列关键字(字符串)的麻烦,我的代码:

self.filteredKeywords=filter(keywords.allValues, {(keyword:NSString) ->                                              
  Bool in
    let words=keyword as? NSString
    return words?.containsString(searchText)
  })

由于AnyObject无法成为NSString的子类型,我仍然坚持这一点!

4 个答案:

答案 0 :(得分:16)

[Swift 2.0更新]

由于NSString是免费桥接到Swift String,所以只需避免强制:

  3> ["abc", "bcd", "xyz"].filter() { nil != $0.rangeOfString("bc") }
$R1: [String] = 2 values {
  [0] = "abc"
  [1] = "bcd"
}

但是,如果您认为allValues不是字符串:

(keywords.allValues as? [String]).filter() { nil != $0.rangeOfString("bc") }

返回一个可选数组。

答案 1 :(得分:4)

您的filter已超过[AnyObject],但关闭时间为NSString。这些需要匹配。此外,您的结果必须是Bool,而不是Bool?。您可以像这样解决这些问题:

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

这会接受AnyObject,然后尝试将其强制转换为NSString。然后是nil-coalleces(??)结果,以确保它始终是Bool

我建议将keywords视为[String:String]而不是NSDictionary。这将摆脱AnyObject的所有复杂情况。然后你可以这样做:

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

尽可能将Foundation集合转换为Swift集合并尽快存储。如果您有传入的Foundation对象,通常可以使用以下技术轻松转换它们:

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

或者您可以执行以下操作来转换它们,以便它们在调试时崩溃(但在发布时默默地“工作”):

func failWith<T>(msg: String, value: T) -> T {
    assertionFailure(msg)
    return value
}

let dict = nsdict as? [String:String] ?? failWith("Couldn't convert \(d)", [:])

答案 2 :(得分:1)

Swift 4.2提供了一种新的方法:

var theBigLebowski = ["The Dude", "Angry Walter", "Maude Lebowski", "Donny Kerabatsos", "The Big Lebowski", "Little Larry Sellers"]

// after removeAll -> ["The Dude", "Angry Walter", "Donny Kerabatsos", "Little Larry Sellers"]
theBigLebowski.removeAll{ $0.contains("Lebowski")}
print(theBigLebowski)

答案 3 :(得分:0)

GoZoner对某些数据类型的答案既有问题,也有一个稍微好一点的方法。以下示例可以显示:

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]

可能不是你想要的那套!

但是,如果我们不将animalArray键入 NSMutableArray ,这种方式就可以正常工作:

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

filteredAnimals: [Otter, Deer]

但我建议使用 $ 0.contains()而不是$ 0.rangeOfString()!= nil ,因为它在两种情况下都能正常运行并略微增强了代码的可读性:

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

filteredAnimals: [Otter, Deer]