【问题标题】:How can I create a method from Array to generate a tuple - Swift如何从 Array 创建一个方法来生成一个元组 - Swift
【发布时间】:2017-02-24 14:38:41
【问题描述】:

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

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

【问题讨论】:

  • 这听起来像是一道作业题。
  • 这是一个例子,不是作业。
  • 那么到目前为止你做了什么?向我们展示你的尝试。
  • @ozgur 查看我的更新
  • 我不明白您为什么要将数组转换为元组,但您在使用 filter 对值进行分组方面处于正确的轨道上。完成后,查看this link 将数组转换为元组。

标签: arrays swift type-conversion tuples


【解决方案1】:

你可以得到原始数组中匹配某个条件的值的个数filtercount像这样:

(以下代码使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2011-12-14
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多