简体   繁体   English

如何在Swift3中将Any转换为Dictionary

[英]How to convert Any to Dictionary in Swift3

I use Alamofire Network request,want to handling error messages, 我使用Alamofire网络请求,想要处理错误信息,

My code : 我的代码:

class NetWorkingEngine: NSObject {
    typealias CreateNetWorkBlockSuccess = (_ responseobject:Any) -> ();
    typealias CreateNetWorkBlockFail = (_ responseobject:NSDictionary) -> ();

    func getDataFun(URL:String,netWorkingBlockSuccess:@escaping CreateNetWorkBlockSuccess,netWorkingBlockField:@escaping CreateNetWorkBlockField) -> Void {
        Alamofire.request(URL).responseJSON { (responseObject) in
            if responseObject.result.isSuccess {
                netWorkingBlockSuccess(responseObject.data!);
            }else{
                netWorkingBlockFail(responseObject.result);
            }
        }
    }
}

But in line 但是排队

netWorkingBlockFail(responseObject.result)

error 错误

cannot convert value of type “Result<Any>” to expected argument type "NSDictionary"

what should I do? 我该怎么办?

update: I want to resquert Error Info, if you error request,Error info is 'Any',But how to 'Error info' convert Dictionary? 更新: I want to resquert Error Info, if you error request,Error info is 'Any',But how to 'Error info' convert Dictionary?

You can convert Any type to Dictionary using [:] type. 您可以使用[:]类型将任何类型转换为字典。 Suppose you have a variable called person which is of type Any; 假设您有一个名为person的变量,其类型为Any; then use the following code: 然后使用以下代码:

let personDictionary = (person as! [String:String])["name"]

...where name is the key in the dictionary. ...其中name是字典中的键。

mySelf Code 我的自己的代码

In NetWorkingTool.swift 在NetWorkingTool.swift中

import UIKit
import Alamofire
class NetWorkingTool: NSObject {
    static let shendInstance = NetWorkingTool()
    private override init() {}

    public func getData(url: String, dataBlock:@escaping (_ resData: Any) ->(), errorBlock:@escaping (_ error: Error) -> ()) -> Void {
        Alamofire.request(url).responseJSON { (responseData) in
            if let json = responseData.result.value {
                dataBlock(json)
            }else{
                errorBlock(responseData.error!)
            }
        }
    }
}

In ViewController.swift 在ViewController.swift中

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NetWorkingTool.shendInstance.getData(url: "you url", dataBlock: { (responseData) in
          guard responseData is [AnyHashable: Any] else{
            print("\(type(of: responseData))")
            let dataArray = responseData as! Array<Any>
            for dict in dataArray {
                let d = dict as! Dictionary<String, AnyObject>
                print(d["title"]!)
            }
            return
        }
        print("\(type(of: responseData))")
        }) { (error) in
            print(error)
        }
    }
}

You can only convert something to a Dictionary if it's in the form < key: value >. 如果它是< key:value >形式,您只能将某些内容转换为Dictionary。 The key must be a Hashable type to ensure that the key is unique. 密钥必须是Hashable类型,以确保密钥是唯一的。

To better understand the issue, play around with this in an Xcode playground project: 为了更好地理解这个问题,请在Xcode playground项目中使用它:

let str: Any = "💩"
testConvert(str)

let dict = ["one": 1, "two": 2]
testConvert(dict)

func testConvert(_ something: Any) {
    guard let dict = something as? [AnyHashable: Any] else {
        print("\(something) couldn't be converted to Dictionary")
        return
    }
    print("\(something) successfully converted to Dictionary")
}

Prints: 打印:

💩 couldn't be converted to Dictionary 💩无法转换为字典

["one": 1, "two": 2] successfully converted to Dictionary [“one”:1,“two”:2]成功转换为Dictionary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM