Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 554
Matthew Folbigg Avatar asked May 12 '16 16:05

Matthew Folbigg


People also ask

How do you use try catch in swift 5?

try – You must use this keyword in front of the method that throws. Think of it like this: “You're trying to execute the method. catch – If the throwing method fails and raises an error, the execution will fall into this catch block. This is where you'll write code display a graceful error message to the user.

How do you declare an int variable in Swift?

Declaring an int variable In Swift, the “var” keyword is used to declare a variable and you don't have to specify the type if it can be inferred from what you're assigning it. Also notice in Swift, we're using the String class as opposed to NSString.


1 Answers

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
like image 143
Daniel Krom Avatar answered Oct 07 '22 18:10

Daniel Krom