Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

ios - 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.

question from:https://stackoverflow.com/questions/65939857/swift-safe-unwrapping-optional-a-class-constant-without-redundancy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add ! end of it's declaration

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...