swift - 在 do{}catch{} 之外使用变量/常量 - swift2

标签 swift try-catch

因此,在按下按钮时,我从一个名为 splitLatitude 的抛出函数创建了 splitLat: [Double],该函数采用 currentLocation: CLLocationCoordinate2D?。然后我想将 splitLat 用作标签(它也将用于其他用途,但这只是示例)

@IBAction func ButtonPress() {
      let splitLat = try self.splitLatitude(self.currentLocation)
      LatSplitLabel.text = "\(splitLat)"
}

这得到一个错误“从这里抛出的错误没有被处理”

我通过将它放在一个 do catch block 中来解决这个问题

    do{
        let splitLat = try self.splitLatitude(self.currentLocation)
    } catch {
        print("error") //Example - Fix
    }

但是当我稍后尝试在 splitLat 上设置标签时是一个“未解析的标识符”

Swift 和一般编程的新手,我是否遗漏了一些基本的东西/我是否有误解?有没有一种方法可以在 do 语句之外使用 do {} 语句中的常量。尝试返回,但这是为功能保留的。

非常感谢任何帮助

谢谢

最佳答案

你有两个选择(我假设 splitLatString 类型)

do{
    let splitLat = try self.splitLatitude(self.currentLocation)
    //do rest of the code here
} catch {
    print("error") //Example - Fix
}

第二个选项,预先声明变量

let splitLat : String? //you can late init let vars from swift 1.2
do{
    splitLat = try self.splitLatitude(self.currentLocation)
} catch {
    print("error") //Example - Fix
}
//Here splitLat is recognized

现在,对您的问题进行一些解释。 在 Swift(以及许多其他语言)中,变量仅在它们定义的范围内定义

范围在这些括号之间定义 {/* 范围代码 */}

{
    var x : Int

    {
        //Here x is defined, it is inside the parent scope
        var y : Int
    }
    //Here Y is not defined, it is outside it's scope
}
//here X is outside the scope, undefined

关于swift - 在 do{}catch{} 之外使用变量/常量 - swift2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192956/

相关文章:

swift - SceneDelegate 和 AppDelegate 的区别

r - 垃圾收集器会在tryCatch语句的替代表达式中释放变量吗?

ios - 在私有(private)数据库中查询 ckzone 中的共享记录不返回任何内容

arrays - 数组或字典扩展中的 Swift 3.0 : compiler error when calling global func min<T>(T, T)

python - 在此程序中使用 try 和 except 在此 python 中

c# - 滥用 try/catch

javascript - 由于性能开销而替换 Nodejs 中的 try/catch

java - 抛出异常与日志记录

ios - 在 Swift 的分段控件中选择任何分段时如何创建和突出显示红色细线(向下)

swift - React Native Push 而不是 Present native iOS View