Swift 3 better way to unwrap an optional

1.1k Views Asked by At

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?

2

There are 2 best solutions below

0
rmaddy On BEST ANSWER

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.

2
OOPer On

This line is completely useless, when myStr.removingPercentEncoding is nil, then nil (right hand side of ??) is assigned to msg:

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

Why don't you make it as:

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

print("msg \(msg)")