Skip to content

Instantly share code, notes, and snippets.

@ClarkGoble
Last active August 29, 2015 14:02
Show Gist options
  • Save ClarkGoble/d84ffa912f0670a0ca6c to your computer and use it in GitHub Desktop.
Save ClarkGoble/d84ffa912f0670a0ca6c to your computer and use it in GitHub Desktop.
Python string and array slicing in Swift
import Foundation
extension Array {
func get (range: Range<Int>) -> Array<T> {
var subarray = Array<T>()
for var i = range.startIndex; i < range.endIndex; i++ {
subarray += [self[i]]
}
return subarray
}
subscript( range: Range<Int>) -> T[] {
var subarray = Array<T>()
let min = range.startIndex
let max = range.endIndex
for var i = min; i < max; i++ {
subarray += [self[i]]
}
return subarray
}
subscript( tup: (Int, Int) ) -> T[] {
var (first, last) = tup
let length = countElements(self)
if first < 0 {
first = length + last
}
if last < 0 {
last = length + last
}
if first > last {
first = last
}
let r:Range = first...last
return Array(self).get(r)
}
}
extension String {
var length: Int {
return countElements(self)
}
func fromTup( tup: (Int, Int) ) -> String {
var (first, last) = tup
let length = countElements(self)
if first < 0 {
first = length + last
}
if last < 0 {
last = length + last
}
if first > last {
first = last
}
let r:Range = first...last
return Array(self).get(r).reduce(String(), combine: +)
}
subscript( range: Range<Int>) -> String {
return Array(self).get(range).reduce(String(), combine: +)
}
subscript( tup: (Int, Int) ) -> String {
var (first, last) = tup
let len = countElements(self)
if first < 0 {
first = length + first
if first < 0 {
first = 0
}
}
if last < 0 {
last = length + last
if last < 0 {
last = 0
}
}
if first > last {
first = last
}
let r:Range = first...last
let s = Array(self).get(r).reduce(String(), combine: +)
return s
}
}
let s : String = "Apple is a string"
let s2 : String = s[(-6,-1)]
let s3 : String = s[1..6]
let a = [1,3,5,7,9]
a[(1,2)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment