类似于JavaScript的Swift数组:swift-javascriptish-arrays

jopen 10年前

swift-javascriptish-arrays 是一个类似 JavaScript的Swift 数组扩展。

push

添加多个元素到一个数组:

var fruits = ["Banana", "Orange"]  fruits.push("Apple")  fruits.push("Kiwi", "Papaya")    // fruits == ["Banana", "Orange", "Apple", "Kiwi", "Papaya"]

pop

移除和返回数组的最后一个元素:

var fruits = ["Apple", "Banana", "Orange"]  var popped = fruits.pop()    // popped == "Orange"  // fruits == ["Apple", "Banana"]

shift

移除和返回数组的第一个项:

var fruits = ["Banana", "Orange", "Apple", "Mango"]  var shifted = fruits.shift()                    // shifted == "Banana"  // fruits == ["Orange", "Apple", "Mango"]

unshift

从数组开始位置添加新元素:

var fruits = ["Banana", "Orange"]  fruits.unshift("Lemon","Pineapple")    // fruits == ["Lemon","Pineapple", "Banana", "Orange"]

concat

假如多个数组,不改变现有的数组,但是会返回一个新的数组:

var yellowFruits = ["Banana", "Lemon"]  var otherFruits = ["Orange", "Apple"]  var allFruits = yellowFruits.concat(otherFruits)    // allFruits == ["Banana","Lemon", "Orange", "Apple"]

 

indexOf

Searches the array for the specified item, and returns its position. The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array. Returns -1 if the item is not found. If the item is present more than once, the indexOf method returns the position of the first occurence.

var fruits = ["Banana", "Orange", "Apple", "Mango"]  var a = fruits.indexOf("Apple")    // a == 2    var fruits = ["Banana", "Orange", "Apple", "Mango", "Banana", "Orange", "Apple"]  var a = fruits.indexOf("Apple", startIndex:4)    // a == 6

join

Joins all elements of an array into a string

var fruits = ["Banana", "Orange", "Apple", "Mango"]  var result = fruits.join()    // result = "Banana,Orange,Apple,Mango"    var fruits = ["Banana", "Orange", "Apple", "Mango"]  var result = fruits.join(separator:" & ")    // result = "Banana & Orange & Apple & Mango"

slice

Returns the selected elements in an array, as a new array object. Method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. The original array will not be changed.

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]  var myBest = fruits.slice(-3, -1)    // myBest == ["Lemon","Apple"]

splice

Adds/removes items to/from an array at position, and return the removed items.

var fruits = ["Banana", "Orange", "Apple", "Mango"]  var spliced = fruits.splice(index:2, howMany:1, elements: "Lemon", "Kiwi")    // spliced == ["Apple"]  // fruits == ["Banana","Orange","Lemon","Kiwi","Mango"]

项目主页:http://www.open-open.com/lib/view/home/1404914045294