0

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()

1 Answer 1

2

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()
}
Sign up to request clarification or add additional context in comments.

4 Comments

there's no error message anymore, but when i'm launching, it's crasking and message is fatal error: unexpectedly found nil while unwrapping an Optional value. As if var initialLocation was nil...
ok, but how could i do that , so ? If initialLocation only exists inside of the if statement ? I have to keep my first code ? no way to be more concise ?
I added a complete solution. The problem with the first set of code is that you're repeating code. This way requires an extra check, but does not repeat any code.
Thx for your help ! i just have let "var" in if statement. After delete them , it's finally working. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.