Swift 2 错误处理和 while

标签 swift swift2

例如下面的代码:

while let data = Provider.getData() {
    ...
}

使用 Swift 2 你会遇到两个错误:
条件绑定(bind)的初始化程序必须具有可选类型,而不是“字符串”
调用可以抛出,但没有标记'try',错误不被处理。

在这里进行错误处理的最佳解决方案是什么……
…如果我想处理这个方法中的错误。
…如果我想抛出错误。

最佳答案

您的 getData( ) 函数返回一个字符串值,而不是一个可选值。因此,您应该使用 ? 将 getData 函数的返回类型更改为可选值类型。运营商

虽然 let 总是需要一个可选值,但如果您的 getData 函数总是返回一个字符串值,那么使用 while let 就没有意义,因为您是故意告诉编译器 getData 函数将始终返回一个字符串值并尝试解包它,所以我们不应该解包一个非可选值。

错误处理代码(Written Keeping Swifter in mind) :

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)
 }

nextLine 函数返回一个字符串,如果生成的数字不等于 3,则告诉“生成的随机数不是 3”,否则它将抛出一个可以在 catch block 中处理的异常。这里我可能使 nextLine 函数成为返回一个可选值。如果我删除?来自 nextLine 函数的返回类型。它会给你一个错误,告诉你“条件值的初始化器必须有可选类型而不是字符串”,这意味着编译器正在尝试解包一个没有意义的非可选值。

考虑:

  var someIntegerValue = 5

  if let x = someIntegerValue
  {
    // it will give an error
  }

上面的代码会给你一个错误,告诉你“条件绑定(bind)的初始化器必须有可选类型,而不是 Int”,因为即使在这里我们也在尝试解包一个非可选值。

 If you replace var some = 5 with var some : Int? = 5 it will be all right.

错误/异常处理:

你可以在获取值之前使用 try 关键字,这个值应该写在 do block 中,它要么获取值,要么触发异常,exception应该在 catch block 内处理。

关于Swift 2 错误处理和 while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30743758/

相关文章:

ios - Segue 和 displayMessage 函数不起作用 - Swift 3/4

ios - 使用 UIBezierPath :byRoundingCorners: with Swift 2 and Swift 3

ios - CGContextDrawImage (Swift) 上的间歇性 "incorrect checksum for freed object"错误

ios - Protocol Delegate 未按预期工作返回 nil swift

swift - 如何执行与时间相关的功能?

ios - Nil 与预期的参数类型 UIViewAnimationOptions 不兼容

json - 从内部具有用户对象的 json 解析用户(使用 Codable)

ios - 即使通过 cocoa pod 安装框架后也没有这样的模块

ios - swift2.0,从 REST 调用返回信息(Alamofire)

ios - 无法调整 UICollectionView 中的单元格间距