【Swift4.0】集合类型-Array

来源:互联网 发布:windows无法检索有关 编辑:程序博客网 时间:2024/06/06 21:05

Swift提供了三个主要的集合类型来存储值的集合:Array,Set,Dictionary。Array是有序的值的集合,Set是无序的不重复的值的集合,Dictionary是无序的键值对集合。

SwiftArraySetDictionary存储的键值的类型都是明确的。这就意味着你不能插入一个错误类型的值到集合里面。同时也就是说,你可以确定从集合里面得到的值的类型。


可变集合


如果你创建了一个Array,Set或者Dictionary,并且把它赋值给了一个变量,那么该集合就是可变的。这就意味着你可以改变该集合:添加,删除,或者改变内容。如果赋值给一个常量,那么该集合就是不可变的,它的内容和大小都不能被改变。


在这里建议大家一个良好的习惯:如果集合不需要改变,那么就创建一个不可变的集合。这样做有助于代码清晰和编译器优化性能。


Array


一个Array用一个有序的列表来存储相同类型的值。相同的值可以在不同的位置出现多次。Swift中这样写:Array<Element>, 其中Element是允许存储值的类型。也可以简写为:[Element].


创建一个空的Array:你可以使用初始化语法来创建某个类型的空Array,如:


var someInts =[Int]()

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

// Prints "someInts is of type [Int] with 0 items.”


根据初始化方法,someInts的类型会被推断为 [Int]。另外,如果代码的上下文中已经提供了类型信息,比如函数参数或者某个类型确定的变量和常量,那么你可以用 [ ] 来创建一个空Array:


someInts.append(3)

// someInts now contains 1 value of type Int

someInts = [ ]

// someInts is now an empty array, but is still of type [Int]


创建一个带缺省值的Array:Swift中Array类型提供了一个初始化方法,可以创建一个固定大小并且所有值都相同的Array。


varthreeDoubles =Array(repeating: 0.0, count: 3)

// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]”


通过两个Array相加来创建一个Array:新的Array的类型通过两个相加的Array的类型决定。


varanotherThreeDoubles=Array(repeating:2.5, count:3)

// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]

 

varsixDoubles=threeDoubles+anotherThreeDoubles

// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]


通过简写的方式来创建一个Array: [Value1, Value2, Value3]  例如:


varshoppingList:[String]=["Eggs", "Milk"]


Swift有类型推断功能,因此根据初始化值的类型,可以推断出shoppingList存储值的类型[String],所以这里也可以不需要String类型:


varshoppingList=["Eggs", "Milk"]


获取和修改Array :你可以通过它的方法或者属性,使用下标索引来获取或者修改Array


获取Array的存储项数量,可以使用它的只读属性count。


var numberOfItems = shoppingList.count;


使用isEmpty属性检查是否count属性为0:


ifshoppingList.isEmpty{

    print("The shopping list is empty.")

}else{

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

}


使用append(_:)方法来添加一个新项:


shoppingList.append("Flour") // 现在shopping list 有三项:"Eggs", "Milk”,"Flour"


或者使用(+=)来附加另外一个Array中的值 :


shoppingList += ["Baking Powder"]


通过下标索引来获取你想获取的值:


varfirstItem =shoppingList[0]


shoppingList[0] ="Six eggs"

// the first item in the list is now equal to "Six eggs" rather than "Eggs”


shoppingList[4...6] = ["Bananas", "Apples"]

// shoppingList now contains 6 items”


通过下标给指定位置插入一个值:使用Array的insert(_:at:)方法


shoppingList.insert("Maple Syrup",at:0)


类似的,删除一个值,使用Array的remove(at:)方法


letmapleSyrup =shoppingList.remove(at:0) //mapleSyrup为返回的删除值


如果要删除最后一项,那么使用removeLast()方法,而不是remove(at:)。这样避免调用count属性。


遍历Array


使用for-in来遍历一个Array的所有值:


foriteminshoppingList {

   print(item)

}


如果你想要知道每项的索引值,那么可以使用enumerated()方法来遍历Array,


for (index,value)inshoppingList.enumerated() {

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

}


原创粉丝点击