What are Swift's counterparts to JavaScript's Array.some() and Array.every()?

后端 未结 2 1145
忘掉有多难
忘掉有多难 2021-01-19 18:33

Swift provides map, filter, reduce, ... for Array\'s, but I am not finding some (or any) or

2条回答
  •  萌比男神i
    2021-01-19 19:02

    To replace any/some, you can use SequenceType's contains method (there's one version which takes a boolean predicate; the other one takes an element and works only for sequences of Equatable elements).

    There's no built-in function like all/every, but you can easily write your own using an extension:

    extension SequenceType
    {
        /// Returns `true` iff *every* element in `self` satisfies `predicate`.
        func all(@noescape predicate: Generator.Element throws -> Bool) rethrows -> Bool
        {
            for element in self {
                if try !predicate(element) {
                    return false
                }
            }
            return true
        }
    }
    

    Or, thanks to De Morgan, you can just negate the result of contains: !array.contains{ !predicate($0) }.

    By the way, these work on any SequenceType, not just Array. That includes Set and even Dictionary (whose elements are (key, value) tuples).

提交回复
热议问题