在swift 3中将数组对象拆分为数组

时间:2018-05-22 12:41:21

标签: swift swift3

我有一个如下数组:

let totalArr = ["First","Second","Third","Fourth","First","Second", "Second"]

我的要求输出是:

let grouper = [["First","First"],["Second", "Second", "Second"],["Third"],  ["Fourth"]]

任何人都可以进行最佳迭代吗?

4 个答案:

答案 0 :(得分:4)

试试这个:)

您可以将任何String数组传递给该函数,它将返回您想要的结果:

func groupArr(totalArr: [String]) -> [Any]{
    var grouperArr = [[String]]()
    for i in totalArr{
        let arr = totalArr.filter({($0 == i)}) as [String]
        if(grouperArr.contains(arr) == false){
            grouperArr.append(arr)
        }
    }
    return grouperArr
}

答案 1 :(得分:4)

 let totalArr = ["First","Second","Third","Fourth","First","Second", "Second"]

 let grouper =   (Dictionary(grouping: totalArr, by: { $0})).map {  $0.value}

 print(grouper)

  let arranged =   (Dictionary(grouping: totalArr, by: { $0})).values
 print(arranged)

答案 2 :(得分:3)

您可以使用Dictionay的分组功能创建一个组,然后获取所有值。

let totalArr = ["First","Second","Third","Fourth","First","Second", "Second"]

let group = Dictionary(grouping: totalArr) { (object) -> String in
    let lowerBound = String.Index(encodedOffset: 0)
    let upperBound = String.Index(encodedOffset: 1)
    return String(object[lowerBound...upperBound])
}
print("group :\(group.values)")

答案 3 :(得分:-2)

迅速5:

extension Array {
    func chunked(into size: Int) -> [[Element]] {
        return stride(from: 0, to: count, by: size).map {
            Array(self[$0 ..< Swift.min($0 + size, count)])
        }
    }
}

如何使用它:

let numbers = Array(1...100)
let result = numbers.chunked(into: 5)

Source