In an article about UserDefaults in iOS development, I saw a code snippet where flatMap is chained to UserDefaults.standard.data like below:
self.isReadStatuses = UserDefaults.standard.data(forKey: "isReadStatuses")
.flatMap { try? JSONDecoder().decode([URL: Bool].self, from: $0) } ?? [:]
Does anyone know Why can we use .flatMap here?
Because
UserDefaults.standard.data(forKey:)returnsData?- anOptional<Data>, andOptionalhas a.flatMapmethod.Specifically here, the
flatMapclosure gets a non-optionalData, and attempts to decode it returning another[URL:Bool]?(also, an optional because oftry?).