因此,在按下按钮时,我正在创建 splitLat: [Double] 从一个名为 splitLatitude 的投掷函数,该函数采用 currentLocation: CLLocationCoordinate2D?。然后我想使用 splitLat 作为标签(它也将用于其他事情,但这只是一个例子)
@IBAction func ButtonPress() {
let splitLat = try self.splitLatitude(self.currentLocation)
LatSplitLabel.text = "\(splitLat)"
}
Run Code Online (Sandbox Code Playgroud)
这得到一个错误“从这里抛出的错误没有被处理”
我通过把它放在一个 do catch 块中来解决这个问题
do{
let splitLat = try self.splitLatitude(self.currentLocation)
} catch {
print("error") //Example - Fix
}
Run Code Online (Sandbox Code Playgroud)
但是当我稍后尝试在 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
}
Run Code Online (Sandbox Code Playgroud)
第二种选择,预先声明变量
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
Run Code Online (Sandbox Code Playgroud)
现在,对您的问题进行一些解释。in Swift
(和许多其他语言)变量仅在它们定义的范围内定义
范围在这些括号之间定义 {/* scope code */ }
{
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2574 次 |
最近记录: |