你可以得到原始数组中匹配某个条件的值的个数,filter和count像这样:
(以下代码使用 Swift 3 编写和测试。)
//The number of values in the original array in the range 0 ..< 50.
let theNumberValuesInRange1 = intArray.filter{0..<50 ~= $0}.count
你可以做同样的事情3次,然后写出这样的东西:
func getTheNumbersInRanges(_ intArray: [Int]) -> (Int, Int, Int) {
let theNumberValuesInRange1 = intArray.filter{0..<50 ~= $0}.count
let theNumberValuesInRange2 = intArray.filter{50..<100 ~= $0}.count
let theNumberValuesInRange3 = intArray.filter{100 <= $0}.count
return (theNumberValuesInRange1, theNumberValuesInRange2, theNumberValuesInRange3)
}
print(getTheNumbersInRanges([52, 5, 13, 126, 17])) //->(3, 1, 1)
但是filter会生成中间数组,所以,特别是对于大数组来说效率不高。
您可以使用reduce,使用它不会生成中间数组。
let theNumberRange1Way2 = intArray.reduce(0) {count, value in 0..<50 ~= value ? count + 1 : count}
将这种方式应用到元组,你可以这样写:
func getTheNumbersInRangesWay2(_ intArray: [Int]) -> (Int, Int, Int) {
return intArray.reduce((0, 0, 0)) {countTuple, value in
switch value {
case 0 ..< 50:
return (countTuple.0 + 1, countTuple.1, countTuple.2)
case 50 ..< 100:
return (countTuple.0, countTuple.1 + 1, countTuple.2)
case let v where 100 <= v:
return (countTuple.0, countTuple.1, countTuple.2 + 1)
default:
return countTuple
}
}
}
print(getTheNumbersInRangesWay2([52, 5, 13, 126, 17])) //->(3, 1, 1)