1

I have an if statement that checks to see if an array element matches a local variable.

 if pinArray.contains(where: {$0.title == restaurantName})

How would I create a variable of this element? I attempted

 let thePin = pinArray.contains(where: {$0.title == restaurantName}) 

but this comes with "could not cast boolean to MKAnnotation".

I also tried variations of

let pins = [pinArray.indexPath.row]
let pinn = pins(where: pin.title == restaurantName) (or close to it)

mapp.selectAnnotation(thePin as! MKAnnotation, animated: true)

to no avail. What basic step am I missing?

enter image description here

5
  • If you actually have code such as if pinArray.contains(where: {$0.title == restaurantName}) { // some stuff } then you can definitely replace that with let thePin = pinArray.contains(where: {$0.title == restaurantName}) followed by if thePin { // some stuff }. Commented Jul 7, 2018 at 6:13
  • Happen to see anything in the update that is causing the signal sibart? Commented Jul 7, 2018 at 6:19
  • Don't post pictures of code. Post code as text. Commented Jul 7, 2018 at 6:21
  • Why are you attempting to force-cast a Bool to a MKAnnotation? thePin is a Bool indicating whether the array contains the value or not. Commented Jul 7, 2018 at 6:21
  • I was attempting to create a variable that is equal to the pin of the pinArray that is equal to/has the same title as restaurantName. Commented Jul 7, 2018 at 6:23

1 Answer 1

1

contains(where:) returns a Bool indicating whether a match was found or not. It does not return the matched value.

So thePin is a Bool which you then attempt to force-cast to a MKAnnotation which of course crashes.

If you want the matching value, change your code to:

if let thePin = pinArray.first(where: { $0.title == restaurantName }) {
    do {
        mapp.selectionAnnotation(thePin, animated: true)
    } catch {
    }
} else {
    // no match in the array
}

No need for contains at all. No need to cast (assuming pinArray is an array of MKAnnotation).

Sign up to request clarification or add additional context in comments.

2 Comments

I have to ask, you've helped me throughout several projects - thanks, haha - but how have you come to know so much? Also, in the if let statement, "first" refers to the first element that matches restaurantName?
Yes, it's the first match. See the documentation for first(where:). And I've been programming since 1979.

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.