0

I know there's a "better" way to get this item that I want, but I'm not as adept yet at Swift's functional programming syntax.

I have a collection of things, they each have a property, I want to find the one with a tag of 1 on that property.

var homeController : UIViewController?
for vc in (tabBarController?.viewControllers)! {
  if vc.tabBarItem.tag == 1 {
    homeController = vc
  }
}

What's your cleaner way to get to "give me the view controller with tab bar item tagged 1"?

bshirley
  • 8,217
  • 1
  • 37
  • 43
  • 4
    Especially see the [very bottom answer](http://stackoverflow.com/a/41637242/2976878) that uses `first(where:)`. Although note that your loop (I suspect inadvertently) actually gets the last element that meets the condition (if intentional, you can use `reversed()` to achieve this). – Hamish Jan 19 '17 at 21:10
  • @Hamish thanks. i was allowing the insufficiency, assuming there was only one correct answer and knowing the list would be short. – bshirley Jan 19 '17 at 22:39

1 Answers1

1

The one liner is:

let homeController: UIViewController? = tabBarController?.viewControllers?.first(where: ({$0.tabBarItem.tag == 1}))
GetSwifty
  • 7,568
  • 1
  • 29
  • 46
  • That was exactly what I was looking for but couldn't find. Thanks. I felt like I was trying to look up a correct spelling in a dictionary. – bshirley Jan 19 '17 at 22:34