我在获取数组的中间索引时遇到错误。这是数组:
CountedArray = ["Jake","Jacob","Sam","Tom","Ben","Joe","Bob","Chen","sara","Simon"]
答案 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