getData() 函数返回一个字符串值,而不是可选值。因此,您应该使用 ? 将 getData 函数的返回类型更改为可选值类型操作员
while let 总是期望一个可选值,如果您的 getData 函数总是返回一个字符串值,那么使用 while let 没有任何意义,因为您故意告诉编译器 getData 函数将始终返回一个 String 值并尝试解开它,所以我们不应该解开非可选值。
错误处理代码(书面保存Swifter心里 )
:
private func nextLine() throws -> String?{
var returnData : String? = ""
if arc4random_uniform(7) != 3 {
returnData = "Genreated Random number other than 3"
}else{
throw NSError(domain: "Generated random number 3", code: 111, userInfo: nil)
}
return returnData
}
do {
while let headerLine = try nextLine() {
//do something with the header
print(headerLine)
}
}catch{
//Handle exception
print(error)
}
如果生成的数字不等于 3,nextLine 函数返回一个字符串,告诉“生成除 3 之外的随机数”,否则它将抛出异常,该异常可以在 catch 块中处理。这里我可能使 nextLine 函数返回一个可选的值。如果我删除?来自 nextLine 函数的返回类型。它会给你一个错误提示“条件值的初始值设定项必须具有可选类型,而不是字符串”,这意味着编译器正在尝试解开一个没有意义的非可选值。
考虑 :
var someIntegerValue = 5
if let x = someIntegerValue
{
// it will give an error
}
上面的代码会给你一个错误,告诉你“条件绑定的初始化程序必须具有可选类型,而不是 Int”,因为即使在这里我们也试图解开可选值。
If you replace var some = 5 with var some : Int? = 5 it will be all right.
错误/异常处理:
你可以利用try获取值之前的关键字应该依次写入里面do块,它要么获取值,要么引发异常,异常应该在内部处理catch block.