1

I am trying to get more Structure into my code so I am implementing this UserDefaultsService:

class UserDefaultsService {
    
    let defaults = UserDefaults(suiteName: UserDefaults.Keys.groupKey)

    static let shared = UserDefaultsService()
    
    func updateDataSourceArrayWithWishlist(wishlist: Wishlist) {
        guard var dataSourceArray = defaults?.getDataSourceArray() else { return }
        if let index = dataSourceArray.firstIndex(where: ({$0.id == wishlist.id})) {
            dataSourceArray[index] = wishlist
            defaults?.setDataSourceArray(data: dataSourceArray)
        }
    }
    
    func getDataSourceArray() -> [Wishlist]? {
        return defaults?.getDataSourceArray()
    }
}

But as you can see defaults is optional. I know I could safe unwrap it with guard for example everytime I am using it but isn' there some better/cleaner way to do this? What I am thinking is to only unwrap it once and then I can use it everywhere in UserDefaultsService.

Chris
  • 1,828
  • 6
  • 40
  • 108
  • You can force unwrap (`!`), but typically what I like to do is to use `guard` to conditionally unwrap or fail with `preconditionFailure` – New Dev Jan 28 '21 at 15:12
  • @NewDev that is what I want to to but I can not use `guard` in a class variable – Chris Jan 28 '21 at 15:14
  • you can use a computed property. Or, you can use an immediately executed closure, i.e. `let default = { guard let ... }()` – New Dev Jan 28 '21 at 15:16

1 Answers1

1

Add ! end of it's declaration

let defaults = UserDefaults(suiteName: UserDefaults.Keys.groupKey)!
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87