【问题标题】:Check if one element in array is contained in string检查数组中的一个元素是否包含在字符串中
【发布时间】:2023-03-13 02:14:01
【问题描述】:
let preferredCountryCurrenciesSymbols = ["USD", "EUR", "GBP", "HKD", "JPY", "RUB", "AUD", "CAD"]
let currency = "USDT"

我需要循环数组并在字符串中搜索 .contains 的代码

我试过了,但没有找到它

Check if array contains part of a string in Swift?

所以基本上我需要的功能是-> Bool有或没有。

【问题讨论】:

  • 你想要什么结果?您是否想要在preferredCountryCurrenciesSymbols 中找到currency 中的值的索引?您是否只想知道currency 中是否找到数组中的任何值?展示您实际尝试过的内容,并清楚地说明您得到的结果与您想要的结果。
  • 如果数组中的任何值在货币内找到

标签: arrays swift string contains


【解决方案1】:

您链接的问题与您需要的相反。

你可以找到数组中的任何值是否包含在currency中:

let preferredCountryCurrenciesSymbols = ["USD", "EUR", "GBP", "HKD", "JPY", "RUB", "AUD", "CAD"]
let currency = "USDT"
if preferredCountryCurrenciesSymbols.first(where: { currency.contains($0) }) != nil {
    print("found")
} else {
    print("not found")
}

【讨论】:

  • 您可以使用contains(where:) 代替first(where:) != nil。附:否决票不是我的,也不知道为什么有人使用。
【解决方案2】:

你可以试试

let found = preferredCountryCurrenciesSymbols.filter { currency.contains($0)}.count != 0 // can use isEmpty also
print(found)

【讨论】:

    【解决方案3】:
    var res = preferredCountryCurrenciesSymbols.contains { element in
                    return element == currency
              }
    

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。这对未来的用户也有帮助。
    【解决方案4】:

    您可以简单地使用 contains(where:) 来完成这项工作。

    if preferredCountryCurrenciesSymbols.contains(where: { currency.contains($0) }) {
        print("currency found...")
    } else {
        print("currency not found...")
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 2019-11-26
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      相关资源
      最近更新 更多