A good way to approach this is with an extension in Swift Array, or in this case a more generalized solution for all BidirectionalCollection objects, including arrays.
, , .
nil, , , , .
extension BidirectionalCollection where Iterator.Element: Equatable {
typealias Element = Self.Iterator.Element
func after(_ item: Element, loop: Bool = false) -> Element? {
if let itemIndex = self.index(of: item) {
let lastItem: Bool = (index(after:itemIndex) == endIndex)
if loop && lastItem {
return self.first
} else if lastItem {
return nil
} else {
return self[index(after:itemIndex)]
}
}
return nil
}
func before(_ item: Element, loop: Bool = false) -> Element? {
if let itemIndex = self.index(of: item) {
let firstItem: Bool = (itemIndex == startIndex)
if loop && firstItem {
return self.last
} else if firstItem {
return nil
} else {
return self[index(before:itemIndex)]
}
}
return nil
}
}
:
, , :
let nextChild = children.after(jane)
, , , , :
let dishwasherTonight = children.after(sammy, loop: true)
, , , .
: endIndex :
, endIndex . - " ", .