Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}
like image 923
Connor Berry Avatar asked Dec 17 '22 23:12

Connor Berry


2 Answers

Similar to first and last, you can extend Array with a computed middle property that returns an optional Element.

extension Array {

    var middle: Element? {
        guard count != 0 else { return nil }

        let middleIndex = (count > 1 ? count - 1 : count) / 2
        return self[middleIndex]
    }

}

Usage Example:

if let middleView = viewList.middle {
    //... Do something
}

I want you to be aware that first and last can return the same element if the array has only 1 element.

Similarly, though this extension will work for any array length, it can return the same element for:

  • first, middle & last if your array has only 1 element
  • middle & last if your array has only 2 elements
like image 57
staticVoidMan Avatar answered Jan 05 '23 11:01

staticVoidMan


Can add an extension to Array to accomplish this:

extension Array {

    var middleIndex: Int {
        return (self.isEmpty ? self.startIndex : self.count - 1) / 2
    }
}
let myArray: [String] = ["Hello", "World", "!"]
print("myArray.middleIndex: \(myArray.middleIndex)") // prints 1
like image 30
Daniel Storm Avatar answered Jan 05 '23 11:01

Daniel Storm