What is the Swift equivalent of C#/.NET/LINQ's Enumerable.All method?

后端 未结 3 1601
囚心锁ツ
囚心锁ツ 2021-01-21 02:43

I want a function that applies a given function to a sequence and returns true iff the given function returns true for every element of the sequence, like Enumerable.All from th

相关标签:
3条回答
  • 2021-01-21 03:02

    Building up on Jon's answer: You can use contains() instead of an (explicit) loop:

    extension SequenceType {
        func all(@noescape predicate: (Self.Generator.Element) throws -> Bool)
            rethrows -> Bool {
                return !(try contains { !(try predicate($0)) })
        }
    }
    
    0 讨论(0)
  • 2021-01-21 03:14

    There isn't a built-in function to do this, but you can easily add your own as a protocol extension method:

    extension SequenceType {
        func all(@noescape predicate: (Self.Generator.Element) throws -> Bool)
            rethrows -> Bool {
    
            for i in self {
                if !(try predicate(i)) { return false }
            }
            return true
        }
    }
    

    and then use it on a sequence like:

    let allPositive = [1, 2, 3].all { $0 > 0 }
    
    0 讨论(0)
  • 2021-01-21 03:19

    Not sure if this helps, but you can achieve the same outcome using reduce. Here's a quick playground I put together to prove the concept:

    let nums = [2, 2, 3, 4]
    
    // Will only evaluate to true if all numbers are even.
    let allEven = nums.reduce(true) {
        if !$0 || $1 % 2 != 0 {
            return false
        }
        return true
    }
    
    0 讨论(0)
提交回复
热议问题