Search code examples
swiftoption-typeoptional-binding

Swift 3 better way to unwrap an optional


Right now I have some code that looks like the following:

let msg: String? = myStr.removingPercentEncoding ?? nil

print("msg \(msg!)")

I really don't like the use of ! in msg! as that can possibly throw an exception, I believe.

What's the best way to call myStr.removingPercentEncoding if myStr is not nil and then unwrap msg without throwing an exception?


Solution

  • The proper way would be:

    if let msg = myStr.removingPercentEncoding {
        print("msg \(msg)")
    }
    

    Here, msg is only valid inside the if statement and only if myStr.removingPercentEncoding isn't nil.

    If you wish to print something if myStr.removingPercentEncoding is nil, then you could and an else:

    if let msg = myStr.removingPercentEncoding {
        print("msg \(msg)")
    } else {
        print("msg has no value")
    }
    

    Read up on Optional Binding in the The Swift Programming Language book.