我有2种结构,Header
和Session
,都符合协议TimelineItem
。
我有一个Array
由TimelineItem
组成,如下所示:
[Header1, SessionA, SessionB, Header2, SessionC, SessionD]
我需要将Session
分组到相关的Header
下,如下所示:
[ [Header1: [SessionA, SessionB], [Header2: [SessionC, SessionD] ]
我尝试使用filter
方法仅检索Header
结构,并使用split
方法检索Session
数组的数组。这些工作正常,但我无法管理如何协调两者以构建我的最终[[Header: [Session]]]
对象。
以下是我的示例代码:
enum TimelineItemType: String {
case Header = "header"
case Session = "session"
}
protocol TimelineItem {
var id: Int { get }
var type: TimelineItemType { get }
var startDate: NSDate { get }
}
Header
结构
struct Header: TimelineItem, Decodable, Hashable, Equatable {
let id: Int
let type: TimelineItemType = .Header
let startDate: NSDate
let text: String
init?(json: JSON) {
guard let id: Int = "id" <~~ json,
let type: TimelineItemType = "type" <~~ json,
let startDate: NSDate = "startDate" <~~ json,
let text: String = "text" <~~ json where type == .Header else {
return nil
}
self.id = id
self.startDate = startDate
self.text = text
}
var hashValue: Int {
// As id is unique, we can use it for hash purpose
return id
}
}
Session
结构
struct Session: TimelineItem, Decodable, Equatable {
let id: Int
let type: TimelineItemType = .Session
let startDate: NSDate
let name: String
let syllabus: String
let speaker: Speaker
let language: String
let room: String
let duration: Int
init?(json: JSON) {
guard let id: Int = "id" <~~ json,
let type: TimelineItemType = "type" <~~ json,
let startDate: NSDate = Decoder.decodeDateISO8601("startDate")(json),
let name: String = "name" <~~ json,
let speaker: Speaker = "speaker" <~~ json,
let syllabus: String = "syllabus" <~~ json,
let language: String = "language" <~~ json,
let room: String = "room" <~~ json,
let duration: Int = "duration" <~~ json where type == .Session else {
return nil
}
self.id = id
self.startDate = startDate
self.name = name
self.speaker = speaker
self.syllabus = syllabus
self.language = language
self.room = room
self.duration = duration
}
}
最后我尝试拆分我的数组代码:
func timelineFromItems(timelineItems: [TimelineItem]) -> [[Header: [Session]]]? {
let slicedSessions = timelineItems.split { $0 is Header }
let sessions = Array(slicedSessions)
let headers = timelineItems.filter { $0.type == .Header }
var timeline = [[Header: [Session]]]()
// HOW TO FILL THE TIMELINE ??
}
如何填充时间表?
答案 0 :(得分:1)
我通过删除所有不必要的信息来减少这个例子
protocol P {}
struct A: P, Hashable {
var i:Int
var hashValue: Int { return i }
}
func ==(lhs: A, rhs: A)->Bool {
return lhs.i == rhs.i
}
struct B: P {
var i:Int
}
// your current data
let arr:[P] = [A(i: 1),B(i: 1),B(i: 2), A(i: 2), B(i: 3), B(i: 4), B(i: 5)]
将您的数据转换为所需格式的功能
func foo(arr: [P])->[[A:[B]]]? {
var dict:[A:[B]] = [:]
var arrb:[B] = []
let arrk:[A] = arr.filter { $0 is A }.map { $0 as! A }
guard var key = arr[0] as? A else { return nil }
arr.forEach { (p) in
if let a = p as? A {
dict[key] = arrb
arrb = []
key = a
}
if let b = p as? B {
arrb.append(b)
}
}
dict[key] = arrb
var arrr:[[A:[B]]] = []
arrk.forEach { (a) in
if let arrb = dict[a] {
arrr.append([a:arrb])
}
}
return arrr
}
现在生成的数组符合您的要求(我希望: - ))
if let result = foo(arr) {
print(result) // [[A(i: 1): [B(i: 1), B(i: 2)]], [A(i: 2): [B(i: 3), B(i: 4), B(i: 5)]]]
}
另一个测试数据
let arr:[P] = [A(i: 1),B(i: 1),B(i: 2), A(i: 2), A(i: 3), B(i: 3)]
给你
[[A(i: 1): [B(i: 1), B(i: 2)]], [A(i: 2): []], [A(i: 3): [B(i: 3)]]]
所以,即使没有B跟随A
,它仍然有效答案 1 :(得分:1)
我没有看到填写时间表的任何障碍,以下是我将如何做到这一点:
func timelineFromItems(timelineItems: [TimelineItem]) -> [[Header: [Session]]]? {
let slicedSessions = timelineItems.split { $0 is Header }
let sessions = Array(slicedSessions)
let headers = timelineItems.filter { $0.type == .Header }
var timeline = [[Header: [Session]]]()
if sessions.count == headers.count { // Check to be sure you have as much header as sessions
for (index, value) in headers.enumerate() {
let dictionary = [value: sessions.getElement(index)]
timeline.append(dictionary)
}
}
return timeline
}
答案 2 :(得分:1)
你实际上可以选择以下简单的东西:
func deserialize(input: [TimelineItem]) -> [Header: [Session]] {
var result = [Header: [Session]]()
var latestHeader: Header! = nil
input.forEach() {
if let header = $0 as? Header {
latestHeader = header
result[header] = []
} else if let session = $0 as? Session {
result[latestHeader]!.append(session)
}
}
return result
}
<强> UPD 强>
不是那么简单,但仍然简洁(上面生成以[Session]
为元素的字典,而@ user3441734指出你需要一个单元素字典数组):
func deserialize(input: [TimelineItem]) -> [[Header: [Session]]] {
var result = [[Header: [Session]]]()
var latestHeader: Header? = nil
input.forEach() {
if let header = $0 as? Header {
latestHeader = header
result.append([header: []])
} else if let session = $0 as? Session, let header = latestHeader {
var headerDict = result.popLast()!
headerDict[header]!.append(session)
result.append(headerDict)
}
}
return result
}
答案 3 :(得分:-2)
感谢大家,我设法满足了我对以下代码的需求:
```
typealias Section = [header: Header, sessions: [TimelineItem]]
private static func groupBySection(timelineItems: [TimelineItem]) -> [Section]? {
let slicedSessions = timelineItems.split { $0.type == .Header }
let headers = timelineItems.filter { $0.type == .Header }
var timeline = [Section]()
for (index, value) in headers.enumerate() {
guard index < slicedSessions.count else {
break
}
let sessionIndex = slicedSessions.startIndex.advancedBy(index)
let arraySessions = Array(slicedSessions[sessionIndex])
let header = value as! Header
let section = (header: header, sessions: arraySessions)
timeline.append(section)
}
return timeline.count > 0 ? timeline : nil
}
```