0

I'm making an API call within Swift and needed help understanding some concepts.

import UIKit

import Foundation

let session = URLSession.shared

let url = URL(string: "https://learnappmaking.com/ex/users.json")


let task = session.dataTask(with: url) { data, response, error in
    print(data)
    print(response)
    print(error)
}

When, I run the code above on XCode, it returns "value of optional type 'URL?' must be unwrapped to a value of type 'URL'"

I'm a beginner in Swift. How would I know when to use force unwrapping, optional binding, or implicitly unwrapped optional to retrieve the data from an optional?

Furthermore, can someone explain to me what URLSession.shared is? I looked through various documentations and the websites state, "a shared singleton session object that gives you a reasonable default behavior for creating tasks." What does a shared singleton object mean and reasonable default behavior look like?

Shreejal Luitel
  • 135
  • 1
  • 7
  • There was the exactly same type of question yesterday here. https://stackoverflow.com/questions/62766098/in-swift-what-is-the-purpose-of-used-for-object-instantiation – El Tomato Jul 08 '20 at 02:08
  • Look at the section for "Optionals" https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html – Han Jul 08 '20 at 02:09

0 Answers0