且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift 3中将NSData转换为数据?

更新时间:2022-04-09 21:47:47

您需要更改几件事.首先,您正在使用NSData.您应该使用Swift类型Data.要从NSData?转换为Data?,只需在变量声明的末尾添加as Data?.

You need to change a couple things. First, you are using NSData. You should be using the Swift type Data. To convert from NSData? to Data?, just add as Data? to the end of the variable declaration.

此外,您的类型是可选的,但是您不能传递可选的类型,因此需要解开它(在本示例中使用if let data = data { /* stuff here */}):

Also, Your type is optional, but you can't pass in an optional type, so you need to unwrap it (using, in this example, if let data = data { /* stuff here */}):

func getAddressForLatLng(latitude: String, longitude: String) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(apikey)")
    let data = NSData(contentsOf: url! as URL) as Data? // <==== Added 'as Data?'
    if let data = data { // <====== Added 'if let'
        let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary
        if let result = json["results"] as? Dictionary {
            if let address = result[0]["address_components"] as? Array {
                let number = address[0]["short_name"] as! String
                let street = address[1]["short_name"] as! String
                let city = address[2]["short_name"] as! String
                let state = address[4]["short_name"] as! String
                let zip = address[6]["short_name"] as! String
                weatherDisplay.text = "\(city),\(state)"
            }
        }
    }
}

更新:

您需要更改的另一件事是:

Another thing you need to change is:

let json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary

当您强制转换为类型Dictionary时,编译器不知道您在说什么,因为Dictionary

When you cast to the type Dictionary, the compiler does not know what you are talking about because Dictionary is a generic type. So you need to cast to Dictionary<String, AnyObject> or [String: AnyObject] (They are the same).