-2

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?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
randombits
  • 47,058
  • 76
  • 251
  • 433
  • 4
    Note that `?? nil` is completely redundant in this case. – Hamish Jan 04 '17 at 17:00
  • By default, `removingPercentEncoding` returns an optional String. It should be: `let msg = myStr.stringByRemovingPercentEncoding` – Ahmad F Jan 04 '17 at 17:04
  • @AhmadF `stringByRemovingPercentEncoding` is the old Swift syntax – shim Jan 04 '17 at 17:06
  • @shim Yes, it's Swift 2, and it returns `String?`. – Ahmad F Jan 04 '17 at 17:09
  • @AhmadF yes, well read the question. It's written in Swift 3. – shim Jan 04 '17 at 17:09
  • @shim Oh, I see... thanks for the note, but it's still the same :) it returns `String?`. You can check it from [the method documentation](https://developer.apple.com/reference/swift/string/1642934-removingpercentencoding). – Ahmad F Jan 04 '17 at 17:13
  • Yes but it is confusing to comment with syntax that will not compile. – shim Jan 04 '17 at 17:14

2 Answers2

4

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

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)")
OOPer
  • 47,149
  • 6
  • 107
  • 142
  • Depending on the use case, it may be more desirable to do `let msg = myStr.removingPercentEncoding ?? myStr`, as seeing the full invalid percent-encoded string may be more useful than seeing nothing. – Hamish Jan 04 '17 at 17:09
  • @Hamish, a possible option, but depends on use case. In some cases, the desired output may be something like `msg --invalid input--`. I think most readers can choose their own alternative value for `""`. – OOPer Jan 04 '17 at 17:16