Hugo75
Hugo75

Reputation: 249

swift / how set global variable in if statement

I have the following code and it's working.

if passedValue == "location1" {
        var initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
        centerMapOnLocation(initialLocation)
        loadInitialData()
        }
if passedValue == "location2" {
        var initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
        centerMapOnLocation(initialLocation)
        loadInitialData()
        }

But to be more concise, i write this , but i ve got the following error message : "Use of unresolved identifier 'initial location'". Any idea ?

if passedValue == "location1" {
        var initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
        }
if passedValue == "location2" {
        var initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
        }

centerMapOnLocation(initialLocation)
        loadInitialData()

Upvotes: 0

Views: 1036

Answers (1)

Caleb
Caleb

Reputation: 5616

Declare var initialLocation: CLLocation! outside and use initialLocation inside.

You probably also want to check if initialLocation is nil before using centerMapOnLocation() just in case.

if initialLocation != nil {
    centerMapOnLocation(initialLocation)
}

Explanation: centerMapOnLocation() can't see initialLocation because it only exists inside of the if statements.

Full code:

var initialLocation: CLLocation!
if passedValue == "location1" {
    initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
}
else if passedValue == "location2" {
    initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
}

if initialLocation != nil {
    centerMapOnLocation(initialLocation)
    loadInitialData()
}

Upvotes: 2

Related Questions