【Swift初见】Swift数组(二)

在苹果的开发文档中对Array还提供了其他的操作算法:

1、Sort函数:

对数组进行排序,根据指定的排序规则,看下面的代码:

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

array.sort{$0 < $1}
println(array)

此时打印出:[2, 3, 4, 5]
其实sort大括号里面是一个闭包,这个以后再学习。
如果倒叙排列,代码如下:
array.sort{$0 > $1}
println(array)

输出为:[5, 4, 3, 2]

2、reverse函数
按照数组的index倒叙排列返回,比如:
let newA = array.reverse()
println(newA)

此时的输出应该为:[2, 3, 4, 5]
可以看出数组倒叙排列了。

3、filter
根据某些条件来筛选数组值:比如:
let newB = array.filter{$0 % 2 == 0}
println(newB)

输出为:[2, 4]

4、map
对当前数组运用闭包内的规则然后返回一个新的数组:
var newArray = array.map{$0 * 3}
println(newArray)

闭包内的规则是每个数字乘以3 所以我们的输出为:[6, 9, 12, 15]

5、reduce
官方解释为:通过闭包内对每个元素进行操作然后返回一个单独的值
比如:
let addRes = array.reduce(2){$0 + $1}
println(addRes)

reduce(2)括号中的2表示初始值,闭包内为操作

我们得到的返回值为: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)



欢迎大家相互学习。





  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值