iosswiftvariablesunwrapswift-optionals

Swift safe unwrapping optional a Class Constant without redundancy


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.


Solution

  • Add ! end of it's declaration

    let defaults = UserDefaults(suiteName: UserDefaults.Keys.groupKey)!