如何在Swift中获取数组的中间索引?

时间:2018-10-05 02:14:35

标签: swift

我在获取数组的中间索引时遇到错误。这是数组:

CountedArray = ["Jake","Jacob","Sam","Tom","Ben","Joe","Bob","Chen","sara","Simon"]

3 个答案:

答案 0 :(得分:0)

关于

let index = CountedArray.count == 0 ? 0 : (CountedArray.count / 2) - 1

答案 1 :(得分:0)

尝试以下代码:

let middle = CountedArray.count / 2
print(CountedArray[middle])

答案 2 :(得分:-1)

这里有一些问题。

  • 如果数组包含odd个元素,则只有一个中间元素
  • 如果数组包含even个元素,则有两个中间元素
  • 如果数组仅包含一个元素,则为中间元素
  • 如果数组仅包含两个元素,则它们都是中间元素
  • 如果数组为empty,则没有中间元素

考虑到上述用例,我可以使用数组类型的扩展名从数组中找到中间元素:

extension Array {
    var middleElements: (first: Element, second: Element?)? {
        if count == 0 {
            return nil
        } else if count.isEven {
            // even number of elements
            let middleIndex = count / 2
            let element1 = self[middleIndex - 1]
            let element2 = self[middleIndex]
            return (element1, element2)
        } else {
            // odd number of elements
            let middleIndex = count / 2
            let element = self[middleIndex]
            return (element, nil)
        }
    }
}

// helper extension
extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }
}

用法:

包含3个元素的数组:

let array = ["One", "Two", "Three"]
if let first = array.middleElements?.first {
    print(first) // Prints Two
}
if let second = array.middleElements?.second {
    print(second)
}

包含2个元素的数组:

let array = ["One", "Two"]
if let first = array.middleElements?.first {
    print(first) // Prints One
}
if let second = array.middleElements?.second {
    print(second) // Prints Two
}

具有1个元素的数组:

let array = ["One"]
if let first = array.middleElements?.first {
    print(first) // Prints One
}
if let second = array.middleElements?.second {
    print(second)
}

空数组:

let array: [String] = []
if let first = array.middleElements?.first {
    print(first)
}
if let second = array.middleElements?.second {
    print(second)
}
// Prints nothing