martinko2499
martinko2499

Reputation: 53

Why Does Swift print "Optional(455 bytes)"

I am working on a weather app, and trying to get the data from an API. But when I type in a city name and hit enter, Swift prints out a message "Optional(455 bytes)" Not sure what goes wrong.

import Foundation

protocol WeatherServiceDelegate{
    func setWeather(weather:Weather)
}

class WeatherService{
    var delegate: WeatherServiceDelegate?

    func getWeather(city: String){
        let path = "http://api.openweathermap.org/data/2.5/weather?q=Boston"
        let url = URL(string: path)

        let task = URLSession.shared.dataTask(with: url!) { (data:Data?, response: URLResponse?, error: Error?) in
            print(data)
        }

        task.resume()

Upvotes: 3

Views: 3922

Answers (4)

MartianMartian
MartianMartian

Reputation: 1859

oh so here's the decoding part, in case anyone are still looking for it.

    if let data = data,
        let urlContent = NSString(data: data, encoding: String.Encoding.ascii.rawValue) {
        print(urlContent)
    } else {
        print("Error: \(error)")
    }

Upvotes: 5

Lampros Tzanetos
Lampros Tzanetos

Reputation: 323

Okay so since you are assigning a value to data you exclude the chance of it remaining = nil. So you can use data! to automatically unwrap the value :

let task = URLSession.shared.dataTask(with: url!) { (data:Data?, response: URLResponse?, error: Error?) in print(data!) }

Upvotes: 0

JAB
JAB

Reputation: 3235

data is of optional type Data?. In Swift, you can unwrap optionals like this:

    if let data = data {
        print(data)
    }

This will mean that inside the if statement data is no longer an optional type and is of type Data. Since it has been unwrapped, it will no longer print the "Optional()" text in the console.

Upvotes: 0

Annie Gupta
Annie Gupta

Reputation: 2822

There's nothing wrong, what you are trying to do is, print an iOS encoded Data from a optional variable data of type Data?

You should rather be checking the response after decoding it.

Cheers!

Upvotes: 2

Related Questions