Alec O'Connor Alec O'Connor - 1 year ago 76
Swift Question

Swift: Determining if cast to integer from string succeeds

Below is my code

func contactForUpdates() -> Int {
//contact server for most recent version
let versionURL = settings.versionURL

if let url = URL(string: versionURL) {
do {
let contents = try NSString(contentsOf: url, usedEncoding: nil)
return Int(contents as String)!
} catch {
// contents could not be loaded
processError("Current version could not be loaded.")
return Int(0)
} else {
// the URL was bad!
processError("Current version could not be loaded--URL was bad.")
return Int(0)

If the URL loads, it will return a single integer. A bad internet connection, such as an airport that requires a login prior to internet access, will not return an integer, but a full HTML page that requests a login. forcing a downcast with
return Int(contents as String)!
will produce the error
fatal error: unexpectedly found nil while unwrapping an Optional value

I assumed that this would run the catch statement when I wrote this, but instead it returns a fatal error. How can I catch this?

Answer Source

If 0 represents an error for you, you could do:

return Int(contents as String) ?? 0

?? is called the "nil coalescing operator". It returns the first value if it's not nil, otherwise it returns the second value.

If you want more robust handling you could use guard

guard let value = Int(contents as String) else {
    processError("Something went horribly wrong")
    return 0

return value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download