【Swift初见】Swift数组(二)
数组 swift
2023-09-11 14:20:59 时间
在苹果的开发文档中对Array还提供了其它的操作算法:
此时打印出:[2, 3, 4, 5]
事实上sort大括号中面是一个闭包,这个以后再学习。
假设倒叙排列,代码例如以下:
输出为:[5, 4, 3, 2]
2、reverse函数
依照数组的index倒叙排列返回,比方:
此时的输出应该为:[2, 3, 4, 5]
能够看出数组倒叙排列了。
输出为:[2, 4]
4、map
对当前数组运用闭包内的规则然后返回一个新的数组:
闭包内的规则是每一个数字乘以3 所以我们的输出为:[6, 9, 12, 15]
5、reduce
官方解释为:通过闭包内对每一个元素进行操作然后返回一个单独的值
比方:
reduce(2)括号里的2表示初始值。闭包内为操作
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)
相关文章
- 【BZOJ3295】动态逆序对(线段树,树状数组)
- 【华为OD机试真题 python】数组连续和 【2022 Q4 | 100分】
- 数据结构之---C语言实现图的数组(邻接矩阵)存储表示
- swift学习之数组
- C# mongodb中内嵌文档数组条件查询
- C#,初学琼林(02)——数组和值计算(Sum,求和)的源程序,相关问题及解决之道
- Swift - 将字符串拆分成数组(把一个字符串分割成字符串数组)
- swift Array 数组
- Swift - 闭包的介绍及用法(以数组排序为例)
- Swift - AppDelegate.swift类中默认方法的介绍
- Swift - 数组排序方法(附样例)
- Swift - 几种使用数组的数据存储模型
- ES5和ES6新增的数组方法
- 在方法体内使用数组
- C++中字符数组与string的相互转换
- 《C#零基础入门之百识百例》(二十七)多维数组 -- 转置矩阵
- 扩展你的javascript数组
- Swift中的数组
- [LeetCode] 4. Median of Two Sorted Arrays 两个有序数组的中位数
- Jquery 遍历数组之$().each方法与$.each()方法介绍