Matthew Folbigg Matthew Folbigg - 6 months ago 10
Swift Question

Using variable/constant outside of do{}catch{} - swift2

So on a button press I'm creating splitLat: [Double] from a throwing function called splitLatitude that takes currentLocation: CLLocationCoordinate2D?. I then want to use splitLat as a Label (its going to be used for other things as well but this serves the example)

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


this gets a error "Errors thrown from here are not handled"

I resolve this by putting it in a do catch block

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


but the when i try to set the label later on splitLat is an "unresolved identifier"

New to swift and programming in general, am i missing something basic/ do i have a mis understanding? is there a way i can use the constant from the do {} statement outside of the do statement. Tried return but that is reserved for functions.

Really appreciate any help

Thanks

Answer

You have two options (I'll assume that splitLat is String type)

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

second option, predeclare the variable

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

Now, some explanation of your problem. in Swift (and many other languages) variables are only defined inside the scope they are defined

scope is defined between these brackets {/* 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