在一个单例类中,我正在尝试以下代码,其中包含存储在字典中的 3 个 URL:
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)
}
但由于某种原因,该行guard let url = urls["en"] else { return }
不足以解开该值:
发生这种情况是因为URL
构造函数可能返回 nil 吗?
还是因为字典可能没有键值?
为什么守卫声明在这里还不够?