0

Is there a way to use if let on an array. If the array has a value at index let it equal this value.

if let view = self.view.subviews({$0.tag == 1 })[0] {
      view.backgroundColor = UIColor.blackColor()
} else {
     print("No view with tag 1")
}

2 Answers 2

1

You can use the filter functionality, and use first instead of [0], to avoid crashes if the filtered array has no elements:

if let view = self.view.subviews.filter{ $0.tag == 1 }.first {
Sign up to request clarification or add additional context in comments.

Comments

0

Swift 3 added the Sequence.first(where:) method, which can replace the calls to filter and first in Cristik's answer.

The advantages of first(where:) over filter { ... }.first are (a) the code becomes marginally clearer and (b) more importantly, better performance when the array is large or the closure is expensive because it stops after finding the first match.

if let view = self.view.subviews.first { $0.tag == 1 } {
    ...
}

Comments

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.