Grant Emerson

Uniformity

Uniformity — SwiftMoji Entry #9

Swift provides the allSatisfy(_:) instance method on Sequences for checking if a condition remains true throughout the contained Elements. It has one parameter: a closure that takes in an Element and returns a Bool. This method removes the cumbersome task of setting up a for-in loop or the convoluted process of checking for uniformity via reduce. The code example utilizes this method to check whether or not the contents of an Array of Animal enum cases match the 🐶 case.

enum Animal {
    case 🐶, 🕷, 🐙, 🦁, 🐊
}

var animals: [Animal] = [.🐶, .🕷, .🐶, .🐊, .🐙, .🐶, .🦁]
animals.removeAll { $0 != .🐶 }
if animals.allSatisfy({ $0 == .🐶 }) {
    print("Yay! You removed all the scary animals!")
}
Tagged with: