使用swift3,我想处理一个错误,
public func titulo()
{do{
marca.snippet=address_components?[1].short_name
marca.title = try (address_components?[2].short_name)!+" "+(address_components?[3].short_name)!
//return titulo
}catch{
marca.title="sin titulo"
}
}
当address_components为nil时调用错误,但在调试中:
我能做些什么来解决这个问题?
答案 0 :(得分:2)
try
/ catch
不会捕获异常,只会抛出错误。在使用隐式解包的选项(!)时,它无助于避免崩溃。警告是一个很好的提示。
答案 1 :(得分:2)
这里有两件事:1)try/catch
,以及2)强制展开可选项。
更新: try/catch
没问题。try/catch
内的代码实际上不是throw
。因此,您不需要try/catch
。
throw
的一个例子是FileManager.contentsOfDirectory
。在Apple's documentation中看起来像这样(注意throws
关键字):
func contentsOfDirectory(at url: URL,
includingPropertiesForKeys keys: [URLResourceKey]?,
options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
您也可以创建自己的函数throw
,但当前的代码却没有。这就是你收到'catch' block is unreachable...
消息的原因。
第二个问题是选项。
Swift中的“可选”可能是nil(空,没有值)。
您的代码包含以下两部分:(address_components?[2].short_name)!
和(address_components?[3].short_name)!
!
标记表示您确定这些物品不会是零! (想想!
告诉系统“是!它不是没有!”同样,想到?
说,“嗯,这是空的吗?这有价值吗?”)< / p>
事实证明,其中一个值是零。因此,斯威夫特不知道该怎么做。撞击和烧伤! ;)
因此,除了try/catch
之外,您还需要在某处guard
语句或if let
语句,以确保您的值不为零。