Swif Array

下面表格列出了數(shù)組的常用方法:

創(chuàng)建一個空數(shù)組

var someInts = [Int]()

print("someInts is of type [Int] with \(someInts.count) items.")

// 打印 "someInts is of type [Int] with 0 items."

someInts.append(3)

// someInts 現(xiàn)在包含一個 Int 值

someInts = []

// someInts 現(xiàn)在是空數(shù)組,但是仍然是 [Int] 類型的。

創(chuàng)建一個帶默認值的數(shù)組

var threeDoubles = [Double](count: 3, repeatedValue:0.0)

// threeDoubles 是一種 [Double] 數(shù)組,等價于 [0.0, 0.0, 0.0]

通過兩個數(shù)組相加創(chuàng)建一個數(shù)組

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)

// anotherThreeDoubles 被推斷為 [Double],等價于 [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles

// sixDoubles 被推斷為 [Double],等價于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

訪問和修改數(shù)組

var shoppingList = ["Eggs", "Milk"]

print("The shopping list contains \(shoppingList.count) items.")

// 輸出 "The shopping list contains 2 items."(這個數(shù)組有2個項)

使用布爾值屬性isEmpty作為檢查count屬性的值是否為 0

if shoppingList.isEmpty {

print("The shopping list is empty.")

} else {

print("The shopping list is not empty.")

}

// 打印 "The shopping list is not empty.

使用append(_:)方法在數(shù)組后面添加新的數(shù)據(jù)項:

shoppingList.append("Flour") ??// shoppingList 現(xiàn)在有3個數(shù)據(jù)項

使用加法賦值運算符(+=)也可以直接在數(shù)組后面添加一個或多個擁有相同類型的數(shù)據(jù)項:

shoppingList += ["Baking Powder"] ??// shoppingList 現(xiàn)在有四項了

shoppingList += ["Chocolate Spread", "Cheese", "Butter"]?// shoppingList 現(xiàn)在有七項了

可以直接使用下標(biāo)語法來獲取數(shù)組中的數(shù)據(jù)項

var firstItem = shoppingList[0] ??// 第一項是 "Eggs"

也可以用下標(biāo)來改變某個已有索引值對應(yīng)的數(shù)據(jù)值:

shoppingList[0] = "Six eggs" ?// 其中的第一項現(xiàn)在是 "Six eggs" 而不是 "Eggs"

利用下標(biāo)來一次改變一系列數(shù)據(jù)值

shoppingList[4...6] = ["Bananas", "Apples"]?// shoppingList 現(xiàn)在有6項

調(diào)用數(shù)組的insert(_:atIndex:)方法來在某個具體索引值之前添加數(shù)據(jù)項:

shoppingList.insert("Maple Syrup", atIndex: 0) // shoppingList 現(xiàn)在有7項

可以使用removeAtIndex(_:)方法來移除數(shù)組中的某一項

let mapleSyrup = shoppingList.removeAtIndex(0)

想把數(shù)組中的最后一項移除,可以使用removeLast()方法

let apples = shoppingList.removeLast()

數(shù)組的遍歷

for item in shoppingList {

print(item)

}

如果我們同時需要每個數(shù)據(jù)項的值和索引值,可以使用enumerate()方法來進行數(shù)組遍歷

for (index, value) in shoppingList.enumerate() {

print("Item \(String(index + 1)): \(value)")

}

// Item 1: Six eggs

// Item 2: Milk

// Item 3: Flour

// Item 4: Baking Powder

// Item 5: Bananas

數(shù)組排序

vararray = [1,4,2,8,3,3,10,9]

letsortedArray = array.sort(<)

print(sortedArray)

array.sortInPlace(>)

print("原數(shù)組排序:", array)


oc ?addObjectsFromArray 在swift中應(yīng)用

var array = [1,2,3,4,5]

let array1 = [6,7,8,9,10]

array += array1

print(array);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容