字典包含一定值swift 3

时间:2016-10-16 06:21:11

标签: dictionary swift3

我想检查字典

中的任何值中是否存在字符串
Dictionary<String, AnyObject>

我知道数组有.contains所以我会认为字典也有。当我开始输入包含

时,Xcode告诉我使用以下内容
countDic.contains(where: { ((key: String, value: AnyObject)) -> Bool in
            <#code#>
        })

我只是不明白如何使用这个我知道里面我需要返回一个Bool,但我不明白我在哪里放了我正在寻找的String。任何帮助都会很棒。

3 个答案:

答案 0 :(得分:10)

contains(where:)检查集合中的任何元素是否满足 给定的谓词,所以在你的情况下它将是

let b = countDic.contains { (key, value) -> Bool in
    value as? String == givenString
}

或直接应用于词典的values视图:

let b = countDic.values.contains { (value) -> Bool in
    value as? String == givenString
}

在这两种情况下都必须(可选)施放AnyObjectString以便将其与给定的字符串进行比较。

使用类型字典会稍微容易些 Dictionary<String, String>因为字符串为Equatable, 并且可以使用contains(element:)方法:

let b = countDic.values.contains(givenString)

答案 1 :(得分:3)

由于Swift 3中的值为AnyObject - Any,因此您必须检查该值是否为字符串。如果是,请检查该值是否包含子字符串。

let countDic : [String:Any] = ["alpha" : 1, "beta" : "foo", "gamma" : "bar"]

countDic.contains { (key, value) -> Bool in
  if let string = value as? String { return string.contains("oo") }
  return false
}

但是,如果您想检查任何值是否等于(而不是包含)字符串,您还可以使用filter函数和isEmpty

!countDic.filter { (key, value) -> Bool in
  value as? String == "foo"
}.isEmpty

答案 2 :(得分:1)

您可能需要首先了解contains(where:)的{​​{1}}的基本用法:

Dictionary

[String: Int]

let myIntDict1: [String: Int] = [ "a" : 1, "b" : 101, "c" : 2 ] let myIntDict1ContainsIntGreaterThan100 = myIntDict1.contains { key, value in //<- `value` is inferred as `Int` value > 100 //<- true when value > 100, false otherwise } print(myIntDict1ContainsIntGreaterThan100) //->true

[String: String]

所以,let myStringDict1: [String: String] = [ "a" : "abc", "b" : "def", "c" : "ghi" ] let myStringDict1ContainsWordIncludingLowercaseE = myStringDict1.contains { key, value in //<- `value` is inferred as `String` value.contains("e") //<- true when value contains "e", false otherwise } print(myStringDict1ContainsWordIncludingLowercaseE) //->true

[String: AnyObject]

所以,在你的情况下:

let myAnyObjectDict1: [String: AnyObject] = [
    "a" : "abc" as NSString,
    "b" : 101 as NSNumber,
    "c" : "ghi" as NSString
]
let myAnyObjectDict1ContainsWordIncludingLowercaseE = myAnyObjectDict1.contains {
    key, value in //<- `value` is inferred as `AnyObject`
    //`AnyObject` may not have the `contains(_:)` method, so you need to check with `if-let-as?`
    if let stringValue = value as? String {
        return value.contains("e") //<- true when value is a String and contains "e"
    } else {
        return false //<- false otherwise
    }
}
print(myAnyObjectDict1ContainsWordIncludingLowercaseE) //->false