2017-11-28 12 views
0

構造体の配列(dateプロパティ)を配列として配列の配列に分割し、各配列に日付を含む項目が含まれるようにしたい同じ暦月。構造体の配列(日付付き)を2次元配列に月単位でグループ化する

私はちょうど私がちょうどvar arrayを作成して、私が行くようにアイテムを堆積配列を反復処理でき

それらetc/groupを分割する方法の周りに私の頭を...取得することはできませんが、私は非常に良くありと信じて(より機能的で、より甘い)方法でそれを行う。

+2

は[スウィフトの配列の要素によってどのようにグループ](https://stackoverflow.com/questions/31220002/how-to-を見てくださいgroup-by-the-array-in-swift)、特に['Dictionary(grouping:by:)']を使ったソリューション(https://developer.apple.com/documentation/swift/辞書/ 2919592-init) –

答えて

0

ここでは非常に高速です:

struct Withdate { 
    let value: String 
    let month: Month 
} 

enum Month: Int { 
    case Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec 
} 

let firstArray = [Withdate(value: "111", month: .Jan), Withdate(value: "112", month: .Jan), Withdate(value: "441", month: .Apr), Withdate(value: "442", month: .Apr), Withdate(value: "991", month: .Sep), Withdate(value: "992", month: .Sep)] 

var objectsDict = [Month: [Withdate]]() 

firstArray.forEach { if objectsDict[$0.month] == nil { objectsDict[$0.month] = [Withdate]() } 
objectsDict[$0.month]!.append($0) } 
let finalArray = Array(objectsDict.values.map{ $0 }) 

print(finalArray) // will return: 

[[main.Withdate(value: "111", month: main.Month.Jan), main.Withdate(value: "112", month: main.Month.Jan)], [main.Withdate(value: "441", month: main.Month.Apr), main.Withdate(value: "442", month: main.Month.Apr)], [main.Withdate(value: "991", month: main.Month.Sep), main.Withdate(value: "992", month: main.Month.Sep)]] 
関連する問題