Initializing CLLocationCoordinate2D

Im am passing an array of type CLLocationCoordinate2D from one controller to another.

However the user sometimes wont be passing any CLLocationCoordinate2D values which means the array in the next viewcontroller will be nil.

Currently Im stuck trying to safely unwrap the optional array and keep getting app crashes from the nil array so thought Id try and just initialize the array instead if no values are passed to it from the previous view controller.


So my array looks like this:

var favCoordinatesArray: [CLLocationCoordinate2D]?


but if I do this:

var favCoordinatesArray: [CLLocationCoordinate2D] = [(0.0, 0.0), (0.0, 0.0)]

Xcode complains and tells me I cant convert type CLLocationCoordinate2D to Doubles.

Im wondering if this will solve my problem.


regards J`

Answered by OOPer in 345069022

It is not difficult to initialize `CLLocationCoordinate2D`:

    var favCoordinatesArray: [CLLocationCoordinate2D]  = [CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)]

But you should better learn how to safely unwrap the optional array, it's the very basic part of Swift and you may need to know how to do if you continue to write an app in Swift.

Accepted Answer

It is not difficult to initialize `CLLocationCoordinate2D`:

    var favCoordinatesArray: [CLLocationCoordinate2D]  = [CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0), CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)]

But you should better learn how to safely unwrap the optional array, it's the very basic part of Swift and you may need to know how to do if you continue to write an app in Swift.

Thanks for that, my errors have gone away now.

Also thanks for your advice, I do understand the concept of optionals, just need more practice 😉


Regards J

Okay if I may quickly use your knowledge on the same topic discussed here.

If my coordinatesArray is empty I should be able to unwrap it safely with an if let so why in this case would it be crashing at the print statement?


Regards J



var coordinatesArray: [CLLocationCoordinate2D]? = []

if let coords = coordinatesArray {
            print("\(coords[0].latitude)")
        }else{return}

Seems very simple. Your `coordinatesArray` can be nil, and when it is not nil, it can be empty. You need to check both.

        guard let coords = coordinatesArray, !coords.isEmpty else {return}
        print("\(coords[0].latitude)")

You may need to know that nil and emptiness are different things in Swift.


And if you have no need to distinguish nil and empty, I recommend you to use non-Optional type for your Array.

var coordinatesArray: [CLLocationCoordinate2D] = []

     guard !coordinatesArray.isEmpty else {return}
     print("\(coordinatesArray[0].latitude)")

Thanks a bunch.

Using guard on the non-optional worked for me.


Regards J

Initializing CLLocationCoordinate2D
 
 
Q