Swift:将组号分配给元组数组中的元组成员

时间:2019-06-10 14:16:41

标签: arrays swift tuples grouping

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

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

我需要根据.group的匹配值向该数组中的每个Touple添加.criterion成员。

.group的值是1...n加1。如果几个元组具有相同的.criterion值,则它们将具有相同的.group值。

如果元组具有唯一的.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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

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
}

答案 1 :(得分:0)

最终基于@Bohdan Savych的解决方案评论:

    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 = 0
          var group = 1
          while index < input.count - 1 {
                if input[index].criterion == input[index + 1].criterion {
                      output[index].group = group
                } else {
                      output[index].group = group
                      group += 1
                } 
                index += 1
          }
          if input[input.count - 1].criterion == input[input.count - 2].criterion {
                output[input.count - 1].group = output[input.count - 2].group
          } else {
                output[input.count - 1].group = (output[input.count - 2].group) + 1
          }
          return output
    }