访问和操作数组:重排操作

2021-07-04  本文已影响0人  一个栗

数组元素的随机化

var array = [Int](1...8)
array.shuffle()
print(array)

运行结果如下:
[5, 4, 8, 7, 6, 1, 2, 3]
var array = [Int](1...8)
var array2 = array.shuffled()
print(array2)

运行结果如下:
[3, 8, 2, 5, 7, 4, 6, 1]

可应用在歌单播放

数组的逆序

var array = [Int](1...8)
array.reverse()
print(array)

运行结果如下:
[8, 7, 6, 5, 4, 3, 2, 1]
var array = [Int](1...8)
var array2 = array.reversed()
print(array)
print(array2)
for i in array2 {
    print(i)
}

运行结果如下:
[1, 2, 3, 4, 5, 6, 7, 8]
ReversedCollection<Array<Int>>(_base: [1, 2, 3, 4, 5, 6, 7, 8])
8
7
6
5
4
3
2
1

数组的分组

var array = [10,20,45,30,98,101,30,4]
let index = array.partition(by: { $0 > 30 })
print(array)
let partition1 = array[..<index]
let partition2 = array[index...]
print(partition1)
print(partition2)

运行结果如下:
[10, 20, 4, 30, 30, 101, 98, 45]
[10, 20, 4, 30, 30]
[101, 98, 45]

数组的排序

var array = [10,20,45,30,98,101,30,4]
array.sort()
print(array)

运行结果如下:
[4, 10, 20, 30, 30, 45, 98, 101]
var array = [10,20,45,30,98,101,30,4]
var array2 = array.sorted()
print(array2)

运行结果如下:
[4, 10, 20, 30, 30, 45, 98, 101]

交换数组两个元素

var array = [10,20,45,30,98,101,30,4]
array.swapAt(array.startIndex, array.endIndex - 1)
print(array)

运行结果如下:
[4, 10, 20, 30, 30, 45, 98, 101]
上一篇下一篇

猜你喜欢

热点阅读