1、Sort函数:
对数组进行排序,根据指定的排序规则,看下面的代码:
var array = [2, 3, 4, 5] array.sort{$0 < $1} println(array)
array.sort{$0 > $1} println(array)
let newA = array.reverse() println(newA)
let newB = array.filter{$0 % 2 == 0} println(newB)
var newArray = array.map{$0 * 3} println(newArray)
let addRes = array.reduce(2){$0 + $1} println(addRes)
我们得到的返回值为:16
PS:Swift还提供了一个Slice类,官方描述如下:
The slice class represents a one-dimensional subset of an array, specified by three parameters: start offset, size, and stride. The start offset is the index of the first element of the array that is part of the subset. The size is the total number of elements
in the subset. Stride is the distance between each successive array element to include in the subset.
For example, with an array of size 10, and a slice with offset 1, size 3 and stride 2, the subset consists of array elements 1, 3, and 5.
简单的说就是Slice是Array的一个子类,包含三个部分:start offset, size, stride。
看个例子:
var slice : Slice = array[1...3] array = Array(slice) slice = Slice(array) println(slice)
原文地址:http://blog.csdn.net/weasleyqi/article/details/41941213