Last active
August 29, 2015 14:13
-
-
Save worthmine/5abf6f35bc22db89e738 to your computer and use it in GitHub Desktop.
it works well!
This file contains 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
extension Array { | |
typealias Element = T | |
mutating func scalar() -> Int { | |
return Int(self.count) | |
} | |
mutating func pop() -> T? { | |
if self.count == 0 { return nil } | |
let removed = self.removeAtIndex(self.endIndex.predecessor()) | |
return removed | |
} | |
mutating func push(values: T...) -> [T] { | |
self.splice(values, atIndex: self.endIndex) | |
return self | |
} | |
mutating func shift() -> T? { | |
if self.count == 0 { return nil } | |
let removed = self.removeAtIndex(self.startIndex) | |
return removed | |
} | |
mutating func unshift(values: T...) -> [T] { | |
// self.insert(values.reverse(), atIndex: self.startIndex) // Error "Array<T> is not convertible to 'T'" | |
for v in values.reverse() { // it works but I wonder why... | |
self.insert(v, atIndex: self.startIndex) | |
} | |
return self | |
} | |
} | |
// Use like bellow | |
var a :Array = ["String", "String2", "String3" ] | |
a.scalar() | |
a.splice(["splice1", "splice2"], atIndex: 1) | |
a.count | |
a.unshift("one", "two") // 配列の挿入 | |
a.unshift("zero") // 1要素の挿入 | |
a.count | |
a.push("push", "push2") // 配列の追加 | |
a.push("push3") // 1要素の追加 | |
a[2] | |
a | |
a.count | |
a.shift() // 先頭の値を取り出し | |
a.pop() // 末尾の値の取り出し | |
a.count | |
// for Int | |
var b :Array = [4, 7, 8 ] | |
b.splice([5, 6], atIndex: 1) | |
b.unshift(1, 2) // 配列の挿入 | |
b.unshift(0) // 1要素の挿入 | |
b.push(9, 10) // 配列の追加 | |
b.push(11) // 1要素の追加 | |
b[2] // 2 | |
b // [0,1,2,3,4,5,6,7,8,9,10,11] | |
b.count // 11 | |
b.shift() // 先頭の値を取り出し | |
b.pop() // 末尾の値の取り出し | |
b.count // 9 | |
// We can't mix the Types in Swft's Array | |
//var c :Array = [a, b, 0] // Error "'Int' is not identical to 'String'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
with typealias, it just works.