使用变量/常量do {} catch {} - swift2

时间:2016-05-12 16:47:59

标签: swift try-catch

所以在一个按钮上按下我创建splitLat:[Double]来自一个名为splitLatitude的thring函数,它接受currentLocation:CLLocationCoordinate2D?。然后我想使用splitLat作为标签(它也将用于其他事情,但这可以作为例子)

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

这会出现错误"从此处抛出的错误不会被处理"

我通过将其放入do catch块来解决这个问题

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

但是我稍后尝试在splitLat上设置标签的时候是"未解析的标识符"

一般来说,swift和编程的新手,我缺少一些基本的东西/我是否理解错误?有没有办法可以使用do语句之外的do {}语句中的常量。尝试返回但是保留用于功能。

非常感谢任何帮助

由于

3 个答案:

答案 0 :(得分:2)

您有两种选择(我假设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(以及许多其他语言)中,变量仅在定义的范围内定义

范围是在这些括号{/* 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

答案 1 :(得分:1)

第三种选择是使用闭包:

 let splitLat:String = { 
     do {
         return try self.splitLatitude(self.currentLocation)
     }
     catch {
         print("error") //Example - Fix
         return ""
     }
 }()
 LatSplitLabel.text = "\(splitLat)"

答案 2 :(得分:0)

如果您想在do / catch块之后成功执行,那么这是一个范围错误。您必须在do / catch范围之外声明变量,以便在执行do / catch之后使用它。

试试这个:

var splitLat: <initialType> = <initialValue>
do {
    let splitLat = try self.splitLatitude(self.currentLocation)
} catch {
    print("error")
}

print(splitLat)

这是一个在Swift 2.2游乐场中运行的炮制示例:

enum Errors: ErrorType {
    case SomeBadError
}

func getResult(param: String) throws -> Bool {
    if param == "" {
        throw Errors.SomeBadError
    }
    return true
}

var result = false
do {
   result = try getResult("it")
} catch {
   print("Some error")
}

print(result)
相关问题