Search code examples
arraysswiftuipageviewcontroller

Select middle value in array - Swift


I'm trying to make sure that the middle value Lists is the first view that is seen when building my application. Xcode offers if let firstView = viewList.first and if let firstView = viewList.last but I can't workout how to select the middle value.

lazy var viewList:[UIViewController] = {
    let sb = UIStoryboard(name: "Main", bundle: nil)

    let lists = sb.instantiateViewController(withIdentifier: "Lists")
    let reminders = sb.instantiateViewController(withIdentifier: "Reminders")
    let todo = sb.instantiateViewController(withIdentifier: "To Do")

    return [reminders, lists, todo]
}()

override func viewDidLoad() {
    super.viewDidLoad()

    self.dataSource = self

    if let firstView = viewList.first {
        self.setViewControllers([firstView], direction: .forward, animated: true, completion: nil)
    }
}

Solution

  • Since viewList declared as [UIViewController] (not as optionals - [UIViewController?]), you don't have to "optional binding" (checking the whether the element is nil or not) because it has to be exist. what you should do instead is to check if the index in the range (making sure that the index is in the range).

    Logically speaking (obviously), if you are pretty sure that viewList always has 3 elements, there is no need to do any check, just:

    let middleViewController = viewList[1]
    

    In case of the number of elements in viewList is undetermined and you are aiming to get the middle element, you simply get it as:

    let middleViewController = viewList[(viewList.count - 1) / 2]
    

    Remember, first and last are optionals, in your case there is no need to work with optionals...