因此,在按下按钮时,我从一个名为 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 {} 语句中的常量。尝试返回,但这是为功能保留的。
非常感谢任何帮助
谢谢
最佳答案
你有两个选择(我假设 splitLat
是 String
类型)
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/