Skip to content

Instantly share code, notes, and snippets.

@IgorMuzyka
Created March 1, 2018 14:19
Show Gist options
  • Save IgorMuzyka/3b109dd65835872fbe22c640d19969f8 to your computer and use it in GitHub Desktop.
Save IgorMuzyka/3b109dd65835872fbe22c640d19969f8 to your computer and use it in GitHub Desktop.
Looped Array Swift 4
public struct LoopedArray<Element>: Sequence, IteratorProtocol {
private let array: [Element]
private var nextIndex: Int = 0
public init(arrayLiteral elements: Element...) {
array = Array(elements)
}
public init<S: Sequence>(_ s: S) where S.Iterator.Element == Element {
array = Array(s)
}
public subscript (index: Int) -> Element {
if index > array.count {
return array[index % array.count]
} else if index < 0 {
if labs(index) >= array.count {
return self[index + array.count]
} else {
return array[array.count + index]
}
} else {
return array[index % array.count]
}
}
public var count: Int {
return array.count
}
public mutating func next() -> Element? {
if nextIndex >= array.count {
nextIndex = nextIndex % array.count
}
return array[nextIndex + 1]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment