Skip to content

Instantly share code, notes, and snippets.

@worthmine
Last active August 29, 2015 14:13
Show Gist options
  • Save worthmine/74dffff8c0f3884b75eb to your computer and use it in GitHub Desktop.
Save worthmine/74dffff8c0f3884b75eb to your computer and use it in GitHub Desktop.
swiftで定義するperl風な配列操作 ref: http://qiita.com/worthmine/items/9d335ce983c04ec15359
class ArrayLikePerl {
var value: [Any] = []
init(_ array :[Any] = []){
value = array
}
func count()->Int {
return self.value.count
}
func pop() -> Any? {
if self.count() == 0 { return nil }
let removed: Any? = self.value.removeAtIndex(self.value.endIndex.predecessor())
return removed
}
func push(value: Any?...) -> Any? {
for v in value {
self.value.insert(v, atIndex: self.value.endIndex)
}
return value
}
func shift() -> Any? {
if self.count() == 0 { return nil }
let removed: Any? = self.value.removeAtIndex(self.value.startIndex)
return removed
}
func unshift(value: Any?...) -> Any? {
for v in value.reverse() {
self.value.insert(v, atIndex: self.value.startIndex)
}
return value
}
}
class hoge {}
let c = hoge()
var b :ArrayLikePerl = ArrayLikePerl(["String", 1, c]) // 初期値を与える。混入可能
b.count() // 3
b.unshift("one", "two") // 配列の挿入
b.unshift("zero") // 1要素の挿入
b.value
b.count() // 6
b.push("push", "push2") // 配列の追加
b.push("push3") // 1要素の追加
b.value[3] // “String”
b.value
b.count() // 9 増えてる
b.shift() // {{Some “zero" }} 配列の先頭を取り出す
b.pop() // {{Some “push3”}} 配列の末尾を切り取る
b.count() // 7 減ってる
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment