In Apple's development documentation, the array also provides additional operational algorithms:
1. Sort function:
Sort the array, according to the specified collation, and look at the following code:
var array = [2, 3, 4, 5]array.sort{$0 < $1}println (array)
Print Now: [2, 3, 4, 5]
In fact, the sort curly braces inside is a closure, this later to learn.
If the flashbacks are arranged, the code is as follows:
array.sort{$0 > $1}println (Array)
Output: [5, 4, 3, 2]
2. Reverse function
Returned by the index flashback of the array, for example:
Let Newa = Array.reverse () println (Newa)
The output should now be: [2, 3, 4, 5]
You can see the array flashbacks.
3. Filter
Filter array values according to certain criteria: for example:
Let newb = array.filter{$0% 2 = = 0}println (newb)
The output is: [2, 4]
4. Map
Apply the rules in the closure to the current array and return a new array:
var NewArray = array.map{$0 * 3}PRINTLN (NewArray)
The rules in closures are multiplied by 3 for each number so our output is: [6, 9, 12, 15]
5. Reduce
The official explanation is that each element is manipulated through a closure and then returns a separate value
Like what:
Let addres = Array.reduce (2) {$ + $1}println (addres)
Reduce (2) The 2 in parentheses represents the initial value, and the action in the closure
The return value we get is: 16
Ps:swift also provides a slice class, which is officially described as follows:
The Slice class represents a one-dimensional subset of an array, specified by three Parameters:start offset, size, and St Ride. The start offset is the index of the first element of the array, which is part of the subset. The size is the total number of elements in the subset. Stride is the distance between each successive an array element to an include in the subset.
For example, with an array of size, and a slice with offset 1, size 3 and Stride 2, the subset consists of array elemen TS 1, 3, and 5.
Simply put, slice is a subclass of array that contains three parts: Start offset, size, stride.
Look at an example:
var slice:slice = Array[1...3]array = Array (slice) slice = slice (array) println (slice)
You are welcome to learn from each other.
Swift's initial initial array (ii)