【问题标题】:Testing if array contains at least one object that has some property [duplicate]测试数组是否包含至少一个具有某些属性的对象[重复]
【发布时间】:2018-05-15 08:36:06
【问题描述】:

我想测试给定的数组是否包含至少一个包含特定“字符串”的对象。有用且可行吗?

【问题讨论】:

  • 添加一些你到目前为止尝试过的代码。

标签: ios swift testing


【解决方案1】:

试试filter()

struct S { let string: String }

let array = [ S(string: "a"), S(string: "b") ]

let hasAtleastOneA = array.filter({ $0.string == "a" }).count > 0

【讨论】:

  • 我可以在单元测试中做这样的事情吗(不是在常规代码中)? :)
  • any 代码中这样做并没有错。如果您有一个大数组并且期望元素接近开头,您可能需要一种让您提前释放的方法,但除此之外,这适用于任何地方。
  • 好吧,没关系:)
【解决方案2】:

类似这样的:

let array = ["a","b","c"]

if array.count > 0 {
    for name in array {
        if name.contains("a"){
            print("YES")
        }

    }
}

【讨论】:

  • 你不需要外部的if,如果找到的话,你应该尽早退出循环。
【解决方案3】:

你检查这样做,

let filtered = data.filter({$0.contains("test")})

Reference Higher order functions in swift: Filter, Map, Reduce, flatmap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2018-03-08
    • 2021-12-26
    • 2015-09-20
    相关资源
    最近更新 更多