【问题标题】:different data type using dictionary in swift?在swift中使用字典的不同数据类型?
【发布时间】:2014-10-06 13:13:15
【问题描述】:

我刚刚了解了 NSURLSession。我想发出 POST 请求。它需要 JSON 作为主体。

在使用 Objective-C 时,我使用了 NSDictionary,但在 swift 中,我的 Dictionary 只包含 1 种数据类型。在 swift 中实现这个的替代方法是什么?

{
    "userID" : "xxxxxxxx",
    "full_name" : "xxxxxxxxx",
    "pob" : "xxxxxxxxxx"
    "dob" : "xxxxxxxxxxx",
    "status" : 3,
    "phone_number" : null,
    "education" : [
        {
            "university" : "xxxxxx",
            "location": {
                latitude: "xxxxxxx",
                longitude: "xxxxxxxx"
             },
             "degree": "xxxxxx"
        },
        {
            "university" : "xxxxxx",
            "location": {
                latitude: "xxxxxxx",
                longitude: "xxxxxxxx"
             },
             "degree": "xxxxxx"
        }
    ]
}

我真的被困住了,我已经寻找了几个小时的解决方案,但没有运气。在 google 中没有找到任何关于此的教程。

非常感谢,对不起我的英语不好。

【问题讨论】:

    标签: ios objective-c json xcode swift


    【解决方案1】:

    只需使用Dictionary<Any, Any>,就像 NSDictionary

    【讨论】:

    • 我不能使用 Any 作为 key,它显示错误 "Type 'Any' does not conform to protocol 'Hashable'"
    • 不需要使用 Any 作为 key。它总是一个字符串。
    • 按照@HotLicks 的建议进行操作。或者你可以使用Dictionary<Hashable, Any>
    【解决方案2】:

    你仍然可以使用NSDictionary:

    var dictionary: NSDictionary = [
        "userID" : "xxxxxxxx",
        "full_name" : "xxxxxxxxx",
        "pob" : "xxxxxxxxxx",
        "dob" : "xxxxxxxxxxx",
        "status" : 3,
        "phone_number" : NSNull(),
        "education" : [
            [
                "university" : "xxxxxx",
                "location": [
                    "latitude" : "xxxxxxx",
                    "longitude" : "xxxxxxxx"
                ],
                "degree": "xxxxxx"
            ],
            [
                "university" : "xxxxxx",
                "location": [
                    "latitude": "xxxxxxx",
                    "longitude": "xxxxxxxx"
                ],
                "degree": "xxxxxx"
            ]
        ]
    ]
    

    为了轻松处理 JSON 响应,您可以使用以下库:

    【讨论】:

    • 我不鼓励使用旧的仅限 Obj-C 的类。无论如何,为图书馆 +1。
    • 同意,但是虽然NSJSONSerialization 没有内置替代方案,但我想NSDictonary 仍然可以使用。
    • 当在 swift 中使用时,返回 NSDictionary 的 Obj-C 方法返回 Swift 的 Dictionary<Any, Any>。返回 NSArray 的方法也是如此。
    【解决方案3】:

    试试这样:-

    var dictionary = Dictionary<String, Any>
    dictionary["userID"] = "xxxxxxxx"
    dictionary["status"] = 200
    like that ...
    

    【讨论】:

    • 我试过了。 NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: nil) 这是错误“类型'Dictionary'不符合协议'AnyObject'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2020-11-05
    • 1970-01-01
    • 2014-07-24
    • 2012-04-23
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多