-1

After completing a loop that places annotations on a map from an array, I want to count the number of annotations.

My code as follows:

let anCount = self.mapView.annotations?.count
            if (anCount > 1) {
//do something
            }

gives error:

Value of optional type 'Int?' must be unwrapped to a value of type 'Int'

The fixit suggestions yield other errors. What is the correct way to count the number of annotations for the map.

Thanks for any suggestions.

user1904273
  • 4,562
  • 11
  • 45
  • 96
  • This has been asked and answered many times: https://stackoverflow.com/search?q=%22Value+of+optional+type%22+%22must+be+unwrapped%22 – Rob Dec 31 '18 at 00:01
  • By the way, be careful of just counting at `annotations` because there might be different types of annotations. E.g., including or excluding the user location on the map (which results in a system generated [`MKUserLocation`](https://developer.apple.com/documentation/mapkit/mkuserlocation) to be added on your behalf) will suddenly change this logic. You really should filter the results for annotations of a particular type... – Rob Dec 31 '18 at 00:14

1 Answers1

1

You have to unwrap the optional, e.g. with if let, which you can then combine with the > 1 test in a single if statement:

if let anCount = mapView.annotations?.count, anCount > 1 {
    //do something
}

But annotations isn't an optional (at least in current iOS versions), so you'd probably just do:

let anCount = mapView.annotations.count
if anCount > 1 {
    //do something
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks for the answer which worked but did you downvote my question cause I took too long to respond? I had a lot going on. In theory, optionals should be simple, but in practice if you are still learning them, each case can be different. – user1904273 Dec 31 '18 at 15:38
  • No, I did not down vote. I was merely suggesting that you research more before posting a question. If you are going to post a question that has been asked before, it’s good to include references of a question or two to demonstrate that you did research it. – Rob Dec 31 '18 at 15:56