Search code examples
swift2option-typeunwrapforced-unwrapping

field has value confirmed but still get unwrap error?


This block of code fails when trying to set appURL, even though the if test succeeds and that the managed object contact has all fields set to non nil values and for certain contact.facebook has a value so I cant see why I am getting found nil while trying to unwrap?

func openFacebook() {

    if (contact.facebook) != nil && (contact.facebook) != "" {

        // build url to users facebook page
        let appURL = NSURL(string: String(format: "fb://profile=%@", contact.facebook!))!

        // build url to user page on facebook web site
        let webURL = NSURL(string: String(format: "http://www.facebook.com/%@", contact.facebook!))!

        openURL(appURL, webURL: webURL)
    }
}

Solution

  • I suggest to do it in a better way like :

    func openFacebook() {
    
        if let contact = contact.facebook where contact != "" {
    
            // build url to users facebook page
            let appURL = NSURL(string: String(format: "fb://profile=%@", contact))!
    
            // build url to user page on facebook web site
            let webURL = NSURL(string: String(format: "http://www.facebook.com/%@", contact))!
    
            openURL(appURL, webURL: webURL)
        }
    }
    

    I think this will a better cleaner way to do nil checks and not force unwraping values later on.