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)
}
}
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 elementmiddle & last if your array has only 2 elementsCan 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With