check if all elements of an array have the same value in Swift

后端 未结 3 1274
执念已碎
执念已碎 2020-12-05 05:05

Is there a function in Swift that checks whether all elements of an array have the same value? In my case, it\'s an array of type Int. I know I can iterate over

3条回答
  •  旧时难觅i
    2020-12-05 05:39

    Soliution for Swift 4.2/Xcode 10:

    let arr = [1, 1, 1, 1]
    let allItemsEqual = arr.dropLast().allSatisfy { $0 == arr.last }
    print(allItemsEqual)
    

    If your current version of Xcode is prior to 10.0 you can find the function allSatisfy of ArraySlice in Xcode9to10Preparation. You can install this library with CocoaPods.

提交回复
热议问题