ios - 按值 Swift 将数组拆分为数组

标签 ios arrays swift

我有一个包含如下数据的数组:[value]#[mode](mode 是可选的)

我想通过 [mode] 将此数组拆分为 [value] 的数组,但保持数据的相同位置,因此对于相同的模式它可以是多个数组:

例如:

let array = ["23.88", "24", "30",  "24.16#C", "25#C", "12#C", "24.44#O", "50#O" , "31", "40" , "44#C", "55#C"]  

// Result 

No mode  ---> [23.88,24,30] 
mode = C ---> [24.16,25,12]
mode = O ---> [24.44,50]
No mode  ---> [31,40] 
mode = C ---> [44,55]

我试过这个扩展,但不是我想要的

extension SequenceType {
    func groupBy<U : Hashable>(@noescape keyFunc: Generator.Element -> U) -> [U:[Generator.Element]] {
        var dict: [U:[Generator.Element]] = [:]
        for el in self {
            let key = keyFunc(el)
            if case nil = dict[key]?.append(el) { dict[key] = [el] }
        }
        return dict
    }
}

它给我这样的结果:

No mode  ---> [23.88,24,30,31,40] 
mode = C ---> [24.16,25,12,44,55]
mode = O ---> [24.44,50] 

最佳答案

我建议您使用数组和元组(保存键)。组成这个数组,然后您可以轻松地将其重新映射为您需要的格式:

let array = ["23.88", "24", "30",  "24.16#C", "25#C", "12#C", "24.44#O", "50#O" , "31", "40" , "44#C", "55#C"]

let noModeTag = "#NoMode"

func group(array: [String]) -> [(String, [Double])]
{
    var result = [(String, [Double])]()

    func addNextElement(number: Double?, _ mode: String?) {
        guard let number = number, mode = mode else {fatalError("input format error")}
        if result.last?.0 == mode {
            var array = result.last!.1
            array.append(number)
            result[result.count - 1] = (mode, array)
        } else {
            result.append((mode, [number]))
        }
    }

    for element in array {
        if element.containsString("#") {
            let separated = element.componentsSeparatedByString("#")
            addNextElement(Double(separated.first ?? "_"), separated.last)
        } else {
            addNextElement(Double(element), noModeTag)
        }
    }
    return result
}

print(group(array))
//[("#NoMode", [23.88, 24.0, 30.0]), ("C", [24.16, 25.0, 12.0]), ("O", [24.44, 50.0]), ("#NoMode", [31.0, 40.0]), ("C", [44.0, 55.0])]

关于ios - 按值 Swift 将数组拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38921864/

相关文章:

ios - ionic 3 Mac build ios cordova-plugin-ionic-webview 出错

ios - Kontakt 信标和 iOS : didStartMonitoringForRegion not working as expected

ios - DJI SDK 获取最后一张图片

c# - 用随机值替换多维数组中的所有项目

swift - 当我调用内部带有 NSTimer 的函数时出现 NSException 错误

ios - 将 "App Groups"权利添加到您的权利文件中吗?

javascript - 带有映射的javascript中以特定格式显示的数组

c - 指针递增

ios - 将自动布局与 UIImageView 一起使用不会保留帧大小

swift - 使用正则表达式在字符串中查找多个引用的单词