Select 数组中的中间值 - Swift

Select middle value in array - Swift

我试图确保中间值列表是构建我的应用程序时看到的第一个视图。 Xcode 提供 if let firstView = viewList.firstif let firstView = viewList.last 但我不知道如何 select 中间值。

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)
    }
}

您的 viewListUIViewController 类型的数组。而 firstlast 仅表示它们的第 0 个和最后一个索引。喜欢:

viewList.first is same as viewList[0]

viewList.last is same as viewList[viewList.count - 1]

Only difference in using these are if you will use viewList.first it will return nil if your array is empty, but if you will use viewList[0] on empty array, you app will be crash with error index out of bound...

因此,您可以使用索引轻松访问您的中间值:

if viewList.count > 1 {
    let middleView = viewList[1]
    self.setViewControllers([middleView], direction: .forward, animated: true, completion: nil)
}

如果您不确定viewList.count会是3个还是更多,那么:

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

类似于 firstlast,您可以使用计算的 middle 属性 扩展 Array,return 是一个可选的 Element.

extension Array {

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

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

}

用法示例:

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

我想让你知道,如果数组只有 1 个元素,firstlast 可以 return 相同的元素。

同样,尽管此扩展适用于任何长度的数组,但它可以 return 相同的元素用于:

  • first, middle & last 如果你的数组只有 1 个元素
  • middle & last 如果你的数组只有 2 个元素

因为 viewList 声明为 [UIViewController](不是可选的 - [UIViewController?]),你不必 "optional binding"(检查元素是否是 nil 或不)因为它 必须 存在。您应该做的是检查索引是否在范围内(确保索引在范围内)。

从逻辑上讲(很明显),如果您非常确定 viewList always 有 3 个元素,则无需进行任何检查,只需:

let middleViewController = viewList[1]

如果viewList中的元素个数未定,而你的目标是获取中间的元素,你只需将其获取为:

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

记住,firstlast 是可选项,在你的情况下不需要使用可选项...

可以向 Array 添加一个扩展来完成此操作:

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