如何在Swift3 iOS中基于键值以升序获取数组

时间:2019-02-09 19:44:46

标签: ios swift sorting dictionary nsmutablearray

我正在Swift3中创建一个数据库应用程序,我必须在其中显示UITableViewJSON中的数据。以下是我的JSON

{
    "Success": 1,
    "data": [{
        "Session_Details": [{
                "Start_Time": "08:00",
                "End_Time": "10:00",
                "Tag_Details": [{
                    "Tag_Id": 1,
                    "Tag_Name": "Test 1",
                    "Tag_Order": 4
                }]
            },
            {
                "Start_Time": "10:30",
                "End_Time": "12:30",
                "Tag_Details": [{
                    "Tag_Id": 2,
                    "Tag_Name": "Test 2",
                    "Tag_Order": 1
                }]
            },
            {
                "Start_Time": "10:30",
                "End_Time": "12:30",
                "Tag_Details": [{
                    "Tag_Id": 3,
                    "Tag_Name": "Test 3",
                    "Tag_Order": 3
                }]
            },
            {
                "Start_Time": "13:30",
                "End_Time": "15:20",
                "Tag_Details": [{
                    "Tag_Id": 1,
                    "Tag_Name": "Test 1",
                    "Tag_Order": 4
                }]
            }
        ]
    }]
}

我已经解析了JSON并获取了所有JSON数据。

我的问题是我必须创建一个具有唯一值的'Tag_Details'数组,这意味着Tag_Id应该是唯一的。另外,我还必须基于ascending键以Tag_Order的顺序设置数组。

我正在尝试下面的代码,但不起作用:

var sessions : [SessionData]! {
        return AgendaDataManager.sharedInstance.sessionData
}

let sortedResults = session.tagDetails!.sortedArray(using: [NSSortDescriptor(key: "tagOrder", ascending: true)])

let sessionTag = ((session.tagDetails as AnyObject).allObjects as! [TagData])[0]

请建议我。谢谢。

1 个答案:

答案 0 :(得分:1)

如果您使用Swift 3进行编码,并且无法使用Codable协议

首先,您应该构建json数据。您可以使用此帮助程序quick type,这将为您提供一个很好的起点:

struct Root {
    let success: Bool
    let data: [Datum]
}

struct Datum {
    let sessionDetails: [SessionDetail]
}

struct SessionDetail {
    let startTime: String
    let endTime: String
    let tagDetails: [TagDetail]
}

struct TagDetail {
    let tagId: Int
    let tagName: String
    let tagOrder: Int
}

您需要为采用Data参数(JSON数据)的根结构创建自定义初始化程序:

typealias Dictionary = [String: Any]
typealias Dictionaries = [[String: Any]]

extension Root {
    init?(_ data: Data) {
        let dictionary = (try? JSONSerialization.jsonObject(with: data)) as? Dictionary ?? [:]
        success = dictionary["Success"] as? Bool == true
        guard success else {
            return nil
        }
        self.data = (dictionary["data"] as! Dictionaries).map(Datum.init)
    }
}

初始化器需要所有结构的字典。

extension Datum {
    init(dictionary: [String: Any]) {
        sessionDetails = (dictionary["Session_Details"] as! Dictionaries)
            .map(SessionDetail.init)
    }
}

extension SessionDetail {
    init(dictionary: [String: Any]) {
        startTime = dictionary["Start_Time"] as! String
        endTime = dictionary["End_Time"] as! String
        tagDetails = (dictionary["Tag_Details"] as! Dictionaries).map(TagDetail.init)
    }
}

extension TagDetail: CustomStringConvertible {
    init(dictionary: [String: Any]) {
        tagId = dictionary["Tag_Id"] as! Int
        tagName = dictionary["Tag_Name"] as! String
        tagOrder = dictionary["Tag_Order"] as! Int
    }
    var description: String {
        return "TagDetail(Id: \(tagId) - Name: \(tagName) - Order: \(tagOrder))"
    }
}

接下来,您需要使TagDetail符合Equatable和Comparable:

extension TagDetail: Equatable, Comparable {
    static func == (lhs: TagDetail, rhs: TagDetail) -> Bool {
        return lhs.tagId == rhs.tagId
    }
    static func < (lhs: TagDetail, rhs: TagDetail) -> Bool {
        return lhs.tagOrder < rhs.tagOrder
    }
}

完成所有这些步骤后,您可以轻松地对对象进行过滤和排序:


let data = Data("""
{
"Success": 1,
"data": [{
"Session_Details": [{
"Start_Time": "08:00",
"End_Time": "10:00",
"Tag_Details": [{
"Tag_Id": 1,
"Tag_Name": "Test 1",
"Tag_Order": 4
}]
},
{
"Start_Time": "10:30",
"End_Time": "12:30",
"Tag_Details": [{
"Tag_Id": 2,
"Tag_Name": "Test 2",
"Tag_Order": 1
}]
},
{
"Start_Time": "10:30",
"End_Time": "12:30",
"Tag_Details": [{
"Tag_Id": 3,
"Tag_Name": "Test 3",
"Tag_Order": 3
}]
},
{
"Start_Time": "13:30",
"End_Time": "15:20",
"Tag_Details": [{
"Tag_Id": 1,
"Tag_Name": "Test 1",
"Tag_Order": 4
}]
}
]
}]
}
""".utf8)

if let root = Root(data), root.success,
    let sessionDetails = root.data.first?.sessionDetails {
    for detail in sessionDetails {
        print(detail)
    }
    let allTagDetails = sessionDetails.flatMap{$0.tagDetails}
    let tagDetailsSorted = allTagDetails.sorted()
    print("\n\n\n")
    var set = Set<Int>()
    let tagDetailsSortedSet = tagDetailsSorted.filter({ set.insert($0.tagId).inserted })
    tagDetailsSortedSet.map{print($0)}
}

这将打印

  

SessionDetail(开始时间:“ 08:00”,结束时间:“ 10:00”,tagDetails:   [TagDetail(Id:1-名称:Test 1-Order:4)])

     

SessionDetail(startTime:   “ 10:30”,结束时间:“ 12:30”,tagDetails:[TagDetail(Id:2-名称:测试2   -订单:1)])

     

SessionDetail(startTime:“ 10:30”,endTime:“ 12:30”,tagDetails:[TagDetail(Id:3-Name:Test 3-Order:3)])

     

SessionDetail(startTime:“ 13:30”,endTime:“ 15:20”,tagDetails:   [TagDetail(Id:1-名称:Test 1-Order:4)])

  

TagDetail(Id:2-名称:Test 2-Order:1)

     

TagDetail(Id:3-名称:Test 3-Order:3)

     

TagDetail(Id:1-名称:Test 1-Order:4)