Checking that all Array elements match value

时间:2016-02-12 21:28:33

标签: ios swift set

I found this as the answer to a different question. It is used to determine if all elements of an Array match.

    var validate = function() {
          // Code to validate form entries
        };

        // Delegate events under the ".validator" namespace
        $( "form" ).on( "click.validator", "button", validate );

        $( "form" ).on( "keypress.validator", "input[type='text']", validate );

        // Remove event handlers in the ".validator" namespace
        $( "form" ).off( ".validator" );

I tried to refactor it so that, it was a Set instead of Array, and a value could be passed in, so you could check if every element of a Set matched the passed in value. But I got no where fast. I think because I also tried to make the value a generic. Any help is much appreciated!

3 个答案:

答案 0 :(得分:4)

A Set is not like an Array. For one thing, a Set is unordered, while an Array is ordered. Even more important, by definition, all Set elements have different values from one another. Therefore they cannot all match the same value. (Except, of course, in the trivial degenerate case where the Set has exactly one element!)

答案 1 :(得分:1)

检查数组的所有元素是否等于给定值

可以稍微缩短一下
extension Array where Element : Equatable {

    func allEqualTo(value: Element) -> Bool {
        return !contains { $0 != value }
    }

}

答案 2 :(得分:0)

因此,在意识到Sets应该只有唯一值,并且我应该使用数组之后,我修改了上面的内容以接受一个值:

func allEqual(value: Element) -> Bool {
    if let first = first {
        if contains(value) {
            return !dropFirst().contains { $0 != first }
        }
        return false
    }
    return false
}
相关问题