Skip to content

Instantly share code, notes, and snippets.

@nuclearace
Last active March 15, 2019 15:15
Show Gist options
  • Select an option

  • Save nuclearace/3ef948a6c951ce12db0d44f1c72d2330 to your computer and use it in GitHub Desktop.

Select an option

Save nuclearace/3ef948a6c951ce12db0d44f1c72d2330 to your computer and use it in GitHub Desktop.
Collection slicing
extension Collection {
func slice(from: Int = 0, to: Int = Int.max, increment: Int = 1) -> [Element] {
let endIdx: Index
let startIdx: Index
if to >= count {
endIdx = endIndex
} else if to < 0 {
endIdx = index(endIndex, offsetBy: to, limitedBy: startIndex) ?? startIndex
} else {
endIdx = index(startIndex, offsetBy: to)
}
if from == 0 {
startIdx = startIndex
} else {
startIdx = index(startIndex, offsetBy: from)
}
if increment == 1 {
return Array(self[startIdx..<endIdx])
}
var res = [Element]()
var curIdx = startIdx
while curIdx != endIdx {
res.append(self[curIdx])
curIdx = index(curIdx, offsetBy: increment, limitedBy: endIdx) ?? endIdx
}
return res
}
}
extension String {
func substring(from: Int, to: Int = Int.max) -> String {
return String(slice(from: from, to: to))
}
}
print("hello🤣 world".substring(from: 5))
print((1...100).slice(from: 1, increment: 2))
print((1...100).slice(from: 1, to: -2, increment: 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment