Renato Pimpão
Renato Pimpão

Reputation: 271

Swift 2.0 - Cannot Subscript a value of type '[CLPlacemark]?'

I'm trying to convert my swift 1.2 app to 2.0. I've tried a few fix's that i found on the internet, but it doesnt work.

Error: Converting to Swift 2.0 - Cannot Subscript a value of type '[CLPlacemark]?'

Code:

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{

    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

        if (error != nil)
        {
            print("Error: " + error!.localizedDescription)
            return
        }

        if placemarks!.count > 0
        {
            let pm = placemarks[0] as! CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            print("Error with the data.")
        }
    })
}

Upvotes: 0

Views: 1256

Answers (2)

R Menke
R Menke

Reputation: 8411

Or with updated Swift 2.0 safety :

guard let currentPlacemarks = placemarks where currentPlacemarks.count > 0 else {
    // error handling here
    return
}

guard let pm = currentPlacemarks[0] where pm is CLPlacemark else {
    // more error handling
    return
}

self.displayLocationInfo(pm)

Upvotes: 1

Renato Pimpão
Renato Pimpão

Reputation: 271

SOLVED:

Replace: let pm = placemarks[0] as! CLPlacemark

For: let pm = placemarks?[0]

Upvotes: 5

Related Questions