Arrays 如何从数组中创建一个方法来生成元组-Swift

Arrays 如何从数组中创建一个方法来生成元组-Swift,arrays,swift,type-conversion,tuples,Arrays,Swift,Type Conversion,Tuples,让数组=[52,5,13,126,17] 我想我要做的是我需要在一个集合上使用过滤器 然后需要在3种不同条件下使用过滤器3次 Filter将返回一个数组,因此我必须使用其计数将其存储在元组中。您可以使用Filter和count获得与特定条件匹配的原始数组中的值数,如下所示: func getTheNumbersInRanges(_ intArray: [Int]) -> (Int, Int, Int) { let theNumberValuesInRange1 = intArray

让数组=[52,5,13,126,17]

我想我要做的是我需要在一个集合上使用过滤器 然后需要在3种不同条件下使用过滤器3次 Filter将返回一个数组,因此我必须使用其计数将其存储在元组中。

您可以使用
Filter
count
获得与特定条件匹配的原始数组中的值数,如下所示:

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)
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)
(以下代码用Swift 3编写和测试。)

将这种方法应用于tuple,可以编写如下内容:

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)
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)
func getTheNumbersInRangesWay2(u阵列:[Int])->(Int,Int,Int){
return intArray.reduce((0,0,0)){countTuple,中的值
开关量{
案例0..<50:
返回(countTuple.0+1,countTuple.1,countTuple.2)
案例50..<100:
返回(countTuple.0,countTuple.1+1,countTuple.2)
案例v,其中100(3,1,1)

这听起来像是一个家庭作业问题。这是一个示例,而不是家庭作业。那么您到目前为止做了什么?向我们展示您的尝试。@ozgur查看我的更新我不明白您为什么要将数组转换为元组,但关于使用
过滤器对值进行分组,您的做法是正确的。完成后,请查看如何转换arr我们把它分成一个元组。