iosswiftuserdefaults

Why can we chain flatMap to UserDefaults.standard.data


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?


Solution

  • Because UserDefaults.standard.data(forKey:) returns Data? - an Optional<Data>, and Optional has a .flatMap method.

    Specifically here, the flatMap closure gets a non-optional Data, and attempts to decode it returning another [URL:Bool]? (also, an optional because of try?).