Skip to content

Instantly share code, notes, and snippets.

@worthmine
Last active August 29, 2015 14:14
Show Gist options
  • Save worthmine/cdcda8dc887e1dfed05b to your computer and use it in GitHub Desktop.
Save worthmine/cdcda8dc887e1dfed05b to your computer and use it in GitHub Desktop.
[Swift]extensionで実装するPerl風のsplice() ref: http://qiita.com/worthmine/items/e859e87d6d46355bd069
extension Array {
typealias Element = T
mutating func splice(var _ atIndex :Int = 0, _ length :Int = 0, _ newElements: T...) -> Slice<T>? {
description
var theIndex = length + atIndex
var spliced :Slice<T> = []
if length < 0 {fatalError("minus length was set")}
if atIndex >= 0 {
if theIndex > self.endIndex {fatalError("Bad Access")}
let preArray = atIndex > 0 ? self[self.startIndex..<atIndex] : []
spliced = length > 0 ? self[atIndex..<theIndex] : []
let postArray = self[theIndex..<self.endIndex]
self = preArray + Array(newElements) + postArray
return length > 0 ? Slice(spliced) : nil
} else { // you can use minus atIndex because it is like Perl
let reversed = self.reverse()
atIndex = abs(atIndex + 1)
theIndex = length + atIndex
if theIndex > self.endIndex {fatalError("Bad Access")}
let postArray = atIndex > 0 ? reversed[reversed.startIndex..<atIndex].reverse() : []
spliced = length > 0 ? reversed[atIndex..<theIndex].reverse() : []
let preArray = theIndex < reversed.endIndex ? reversed[theIndex..<reversed.endIndex].reverse() :[]
self = preArray + Array(newElements) + postArray
return length > 0 ? Slice(spliced) : nil
}
}
}
a.splice(-1, 0, "push" ) // push()
a.splice(-1, 1 ) // pop()
a.splice(0, 0, "unshift" ) // unshift()
a.splice(0, 1) // shift()
a // -> ["Four", "Five", "Six", "Seven", "Eight"]
a.splice(0, a.count, "other", "Strings", "like", "those")
a // -> ["other", "Strings", "like", "those"]
a.splice(-2, 2) // -> ["Strings", "like"]
a = ["Four", "Seven", "Eight" ]
a.splice(["Five", "Six"], atIndex: 1) // using a default splice
a.splice(2, 2, "Six2", "Seven2") // -> {["Seven", "Eight"]} // using mutating splice
a.splice(0, 1)  // -> {[“Four"]}
var a :Array = ["Four", "Seven", "Eight" ]
a.splice(["Five", "Six"], atIndex: 1) // -> ["Four","Five","Six",”Seven”,”Eight"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment