Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Any to Dictionary in Swift3

Tags:

ios

swift3

I use Alamofire Network request,want to handling error messages,

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?

like image 997
Ghost Clock Avatar asked Mar 15 '17 01:03

Ghost Clock


3 Answers

You can convert Any type to Dictionary using [:] type. Suppose you have a variable called person which is of type Any; then use the following code:

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

...where name is the key in the dictionary.

like image 69
Prashant Humney Avatar answered Oct 20 '22 03:10

Prashant Humney


You can only convert something to a Dictionary if it's in the form <key: value>. The key must be a Hashable type to ensure that the key is unique.

To better understand the issue, play around with this in an Xcode playground project:

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

like image 2
Karoly Nyisztor Avatar answered Oct 20 '22 03:10

Karoly Nyisztor


mySelf Code

In 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

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)
        }
    }
}
like image 1
Ghost Clock Avatar answered Oct 20 '22 05:10

Ghost Clock