标签:
在开发中,数组这个概念我们应该很熟悉了,Objective-C 中为我们提供了 NSArray 作为数组的实现。大家应该对很熟悉了。而在 Swift 中,为我们提供了它自己对于数组的实现,也是这里我们要介绍的,就是 Array 类。
Array 的官方文档可以参看这里: SwiftStandardLibraryReference
废话不多说,下面就开始我们的主题啦。
<!-- more -->
我们要使用一个数组,首先要做的就是创建它,Array 类为我们提供了几种方式来创建:
var emptyArray = Array<Int>()
我们这里声明了一个空的数组,数组的元素是 Int 类型,我们还可以这样初始化数组:
var equivalentEmptyArray = [Int]()
这样的写法和前面那个的效果是一样的。我们还可以这样进行初始化:
let numericArray = Array(count: 4, repeatedValue: 5)
// 数组元素为 [5,5,5,5]
这个初始化方法,里面使用 4 个数字 5 来填充这个数组,并且数组元素的类型为 Int。
我们的数组创建完成后,我们就可以通过下标来引用它里面的元素了:
var weekdays = ["monday","tuesday","wednesday","thursday"]
println(weekdays[1]) //输出 tuesday
我们还可以通过下标来修改数组中的元素:
var weekdays = ["monday","tesday","today","thursday"]
weekdays[2] = "wednesday"
//修改后的数组元素 ["monday","wednesday","today","thursday"]
但我们不能通过下标修改 let 关键字定义的常量数组:
let weekdays = ["monday","tesday","today","thursday"]
weekdays[2] = "wednesday" //报错
Swift 还提供了范围的下标访问:
let weekdays = ["monday","wednesday","today","thursday"]
let subdays = weekdays[0...2]
//subdays 的数组元素 ["monday","wednesday","today"]
我们用 arr[0...2] 这种形式的索引,就可以访问到数组中某一区域的元素了,这点从上面的例子中就能看出来啦。
我们甚至还可以用范围索引来设置数组的元素,前提是这个数组是用 var 定义的:
var weekdays = ["monday","wednesday","today","thursday"]
weekdays[0...1] = ["today","tomorrow"]
//数组的元素 ["today","tomorrow","today","thursday"]
标签:
原文地址:http://blog.csdn.net/lizhengduan/article/details/43058793