In a singleton class I am trying the following code with 3 URLs stored in a dictionary:
class DownloadManager {
static let instance = DownloadManager()
let urls = [
"en" : URL(string: "https://wordsbyfarber.com/ws/top"),
"de" : URL(string: "https://wortefarbers.de/ws/top"),
"ru" : URL(string: "https://slova.de/ws/top")
]
var cancellables = Set<AnyCancellable>()
private init() {
getTops()
}
func getTops() {
guard let url = urls["en"] else { return }
URLSession.shared.dataTaskPublisher(for: url) // COMPILE ERROR
.tryMap(handleOutput)
.decode(type: TopResponse.self, decoder: JSONDecoder())
.sink { completion in
print(completion)
} receiveValue: { fetchedTops in
// ... store entities in Core Data
}
.store(in: &cancellables)
}
But for some reason the line guard let url = urls["en"] else { return }
is not sufficient to unwrap the value:
Is this happening because the URL
constructor might return nil?
Or because of the dictionary might not have a value for a key?
And why is guard statement not enough here?