You have two things going on here: 1) the try/catch
, and 2) force-unwrapping of an optional.
Update: The try/catch
is fine. The code you have inside the try/catch
actually doesn't throw
. Therefore, you don't need the try/catch
there.
An example of something that does throw
is FileManager.contentsOfDirectory
. It looks like this in Apple's documentation (notice the throws
keyword):
func contentsOfDirectory(at url: URL,
includingPropertiesForKeys keys: [URLResourceKey]?,
options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
You can make your own functions throw
as well, but your current code doesn't. That's why you get the 'catch' block is unreachable...
message.
The second issue is with the optionals.
An "optional" in Swift is something that could possibly be nil (empty, without a value).
Your code has these two parts: (address_components?[2].short_name)!
and (address_components?[3].short_name)!
The !
marks are saying that you're CERTAIN that these items won't be nil! (Think of the !
as telling the system "YES! IT'S NOT NIL!" Likewise, think of the ?
as saying, "Umm, is this empty? Does this have a value?")
As it turns out, one of those values IS nil. Therefore, Swift doesn't know what the heck to do with it. CRASH AND BURN! ;)
So, in addition to your try/catch
, you're going to need some guard
statements or if let
statements somewhere to make sure your values are not nil.