Johny D Good
Johny D Good

Reputation: 427

checking for an optional UserDefaults.standard.value

I check if I have user's Facebook data as UserDefaults.standard.value

if let facebookDetails:Dictionary = (UserDefaults.standard.value(forKey: "facebookDetails") as? [String:Any])! {
        dump(facebookDetails)

        let picture:Dictionary = (facebookDetails["picture"]  as? [String:Any])!
        let fb_pic_data:Dictionary = (picture["data"]  as? [String:Any])!
        let fb_pic_data_url:String = fb_pic_data["url"] as! String
            if let checkedUrl = URL(string: fb_pic_data_url) {
                profiler.contentMode = .scaleAspectFit
                downloadImage(url: checkedUrl)
                profiler.layer.borderWidth = 1
                profiler.layer.masksToBounds = false
                profiler.layer.borderColor = UIColor.black.cgColor
                profiler.layer.cornerRadius = profiler.frame.height/2
                profiler.clipsToBounds = true
            }
        }

I get the following alert: Non-optional expression of type '[String: Any]' used in a check for optionals

and app crashes if UserDefaults.standard.value(forKey: "facebookDetails") is unset.

What is the correct way of writing this conditional if?

Thanks

Upvotes: 1

Views: 1000

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You are completely misusing optionals, forced-unwrapping, and if let.

You should also avoid using value(forKey:). And avoid needless type declarations. Let Swift infer the type when appropriate.

Your if should be:

if let facebookDetails = UserDefaults.standard.dictionary(forKey: "facebookDetails") {
}

You should also avoid the force-unwrapping unless you know for sure that the value (or cast) will always succeed.

And be consistent in your code. On one line you do:

let picture:Dictionary = (facebookDetails["picture"]  as? [String:Any])!

and another you do:

let fb_pic_data_url:String = fb_pic_data["url"] as! String

Why take two different approaches to forcing the case and the optional?

Upvotes: 4

Related Questions