首页 > 解决方案 > Swift:将组号分配给元组数组中的元组成员

问题描述

我有一些元组数组,其定义如下:

[(description: [String], criterion: Int, relative: Double, average: Int, type: String, group: Int)]并按减少排序.criterion

我需要.group根据.criterion.

.group的值1...n增加 1。如果多个元组具有相同的 值.criterion,那么它们将具有相同的 值.group

如果 Tuple 具有 unique .criterion,那么它只有一个具有唯一.group值。

我正在尝试在下面的代码中执行此操作:

func appendingGroup(_ input: [(description: [String], criterion: Int, relative: Double, average: Int, type: String, group: Int)]) -> [(description: [String], criterion: Int, relative: Double, average: Int, type: String, group: Int)] {
var output: [(description: [String], criterion: Int, relative: Double, average: Int, type: String, group: Int)] = []
var index = 1
while index < input.count - 1 {
    if input[index].criterion != input[index + 1].criterion && input[index].criterion != input[index - 1].criterion {
        print(index)
        output[index].group = index
    }
    index += 1
}
return output}

这是基于@Nicolai Henriksen 问题Swift: loop over array elements and access previous and next elements

但我[]在我的output.

我做错了什么?

标签: arraysswifttuplesgrouping

解决方案


你变空的原因output是你没有修改它。

尝试改变

var output: [(description: [String], criterion: Int, relative: Double, average: Int, type: String, group: Int)] = []

var output = input

完整

typealias Type = (description: [String], criterion: Int, relative: Double, average: Int, type: String, group: Int)

func appendingGroup(_ input: [Type]) -> [Type] {
    guard input.count > 2 else { return input } // without this check app will crash for arrays that are less than 2
    var output = input
    var index = 1

    while index < input.count - 1 {
        if input[index].criterion != input[index + 1].criterion && input[index].criterion != input[index - 1].criterion {
            output[index].group = index
        }

        index += 1
    }

    return output
}

推荐阅读