類似于JavaScript的Swift數組:swift-javascriptish-arrays

jopen 10年前發布 | 19K 次閱讀 Apple Swift開發 swift-javascriptish-arrays

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.baiduhome.net/lib/view/home/1404914045294

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!