【问题标题】:Is it possible to check whether a String matches a String in an Array or Dictionary, Swift?是否可以检查字符串是否与数组或字典中的字符串匹配,Swift?
【发布时间】:2014-07-01 13:03:12
【问题描述】:

在这里玩 Swift,这可能是一个愚蠢的问题,但是否可以检查字符串是否与数组或字典中的字符串匹配?

例如

if string == array.String {
}

if string== dictionary.String {
}

我意识到这些例子很愚蠢,但只是为了展示我的想法。 谢谢。 :)

【问题讨论】:

  • 我无法从您的“示例”中识别出您在想什么。你想检查一个数组是否包含给定的字符串吗?一些具体的例子会有所帮助。
  • 是的,这正是我想要做的。对不起,愚蠢:P

标签: arrays string if-statement dictionary swift


【解决方案1】:

对于数组,您可以使用find() 函数。它返回一个可选的Int,它可以是 针对nil进行测试:

let array = [ "a", "b", "c"]
let searchTerm = "b"
let found = find(array, searchTerm) != nil
println(found)

这适用于任意数组,而不仅仅是字符串数组。

对于字典dict,同样的方法可以应用于dict.keysdict.values, 根据您的要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    相关资源
    最近更新 更多