Created
March 1, 2018 14:19
-
-
Save IgorMuzyka/3b109dd65835872fbe22c640d19969f8 to your computer and use it in GitHub Desktop.
Looped Array Swift 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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