导语
近日一直在研究函数式编程,看
Array
函数使用,特想总结一下Array
各种函数方法的使用
joined
拼接一个元素序列生成一个字符串,而且还可以在两个元素中间添加分隔符
直接上代码
<pre>let cast = ["Hello","World","张三","李四"]
let string = cast.joined()
// string = HelloWorld张三李四
//添加分隔符使用方法
let sepString = cast.joined(separator:".")
// sepString = Hello.World.张三.李四
</pre>
lexicographicallyPrecedes
按顺序比较连个集合的值,如果第一个集合小于第二个则返回 true
,反之返回false
<pre>
let a = [1,2,3,4]
let b = [1,2,2,2]
let c = a.lexicographicallyPrecedes(b)
// c = false
let c = b.lexicographicallyPrecedes(a)
// c = true
</pre>
max/min
很明显这是要找出数组中的最大和最小值,使用也非常简单直接在数组后面加max()
/min()
,如果数组为空则 返回 nil
<pre>
let a = [1,2,3,4]
let max = a.max() // max = 4
let min = a.min() // min = 1
</pre>
但数组是字典数组的时候需要用max(by:)
/min(by:)
来定义比较key
还是value
,如果数组为空则 返回 nil
<pre>
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
//比较字典的value
let greatestHue = hues.max { a, b in a.value < b.value }
// greatestHue = (key: "Heliotrope", value: 296)
//比较字典的value
let greatestHue = hues.max { a, b in a.value < b.value }
// greatestHue = (key: "Coral", value: 16)
</pre>
sorted/sorted(by: )
对数组进行排序:sorted
默认的是升序,可以通过sorted(by: >)
改为降序
<pre>
let a = [1,3,2,4]
b = a.sorted() // b = [1,2,3,4]
c = a.sorted(by: >) // c= [4,3,2,1]
</pre>
elementsEqual
判断两个数组是否有相同的元素相同的顺序,如果相同返回true
,不同返回false
<pre>
let a = 1...3
let b = 1...10
print(a.elementsEqual(b))
// Prints "false"
print(a.elementsEqual([1, 2, 3]))
// Prints "true"
print(a.elementsEqual([3,2,1]))
//Prints “false”
</pre>
starts/starts(with:by:)
判断以第一个数组开始是否包含第二个数组,通过starts(with:by:)
可以添加条件,第一个数组开始的元素大于或者小于或者等于第二个数组第二个数组
<pre>
let a = 1...3
let b = 1...10
let c = 2...6
//start可以翻译为b是以a开始的,如果a为空数组,返回为true
print(b.starts(with: a)) //true
print(a.starts(with: b)) //false
//从开始开始c中的每个元素都比a中相同下标的元素要大,如果a为空数组,返回为true
print(c.starts(with: a, by: { (q, w) -> Bool in
return q > w
})) //true
</pre>
replaceSubrange
替换掉某个区域的元素通过相同的某个元素
<pre>
var nums = [10, 20, 30, 40, 50]
nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
print(nums) //[10,1,1,1,1,1,50]
</pre>
dropLast
去掉数组后面的几个元素
<pre>
let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
</pre>
suffix
从最后开始选择元素,形成新的数组
<pre>
let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
</pre>
map
遍历数组,不改变数组序列,返回相同或不同类型的数组
<pre>
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercaseString }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.characters.count }
// 'letterCounts' == [6, 6, 3, 4]
</pre>
flatMap
flatMap 与 map 不同之处是
1、flatMap返回后的数组中不存在 nil 同时它会把Optional解包;
<pre>
let fruits = ["apple", "banana", "orange", ""]
let counts = fruits.flatMap { fruit -> Int? in
let length = fruit.characters.count
guard length > 0 else {
return nil
}
return length
}
// [5,6,6]
print(counts)
</pre>
2、flatMap 还能把数组中存有数组的数组 一同打开变成一个新的数组 ;
<pre>
let array = [[1,2,3], [4,5,6], [7,8,9]]
// 如果用map来获取新的数组
let arrayMap = array.map { $0 }
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(arrayMap)
// 用flatMap
let arrayFlatMap = array.flatMap { $0 }
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(arrayFlatMap)
</pre>
f3、latMap也能把两个不同的数组合并成一个数组 这个合并的数组元素个数是前面两个数组元素个数的乘积
<pre>
// 这种情况是把两个不同的数组合并成一个数组 这个合并的数组元素个数是前面两个数组元素个数的乘积
let fruits = ["apple", "banana", "orange"]
let counts = [1, 2, 3]
let fruitCounts = counts.flatMap { count in
fruits.map { fruit in
// title + "(index)"
// 也可以返回元组
(fruit, count)
}
}
// [("apple", 1), ("banana", 1), ("orange", 1), ("apple", 2), ("banana", 2), ("orange", 2), ("apple", 3), ("banana", 3), ("orange", 3)]
print(fruitCounts)
// 这种方法估计用的很少 可以算是一个 flatMap 和 map 的结合使用吧
</pre>
reversed
数组倒叙
<pre>
let numbers = [3, 5, 7]
for number in numbers.reversed() {
print(number)
}
// Prints "7"
// Prints "5"
// Prints "3"
</pre>
filter
数组选择合适的元素,形成一个新的数组
<pre>
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.characters.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"
</pre>
first
选出第一个符合条件的元素
<pre>
let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
print("The first negative number is (firstNegative).")
}
// Prints "The first negative number is -2."
</pre>
enumerated
遍历字典,可以分开序号和值
<pre>
let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [SetIndex<String>] = []
for (i, name) in names.enumerated() {
print(i, name)
}
//0 Nicolás
//1 Martina
//2 Camilla
//3 Mateo
//4 Sofia
</pre>
contains
遍历数组,查看数组是否包含符合条件的,有则返回true
,没有则返回false
<pre>
let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 }
// 'hasBigPurchase' == true
</pre>
reduce
1、想要获取一个数组的和或者乘积,可使用此方法,此处以和为例
<pre>
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
</pre>
2、 合并成的新值不一定跟原数组中元素的类型相同
<pre>
let numbers = [1,5,1,8,8,8,8,8,8,8,8]
// reduce 函数第一个参数是返回值的初始化值
let tel = numbers.reduce("") { "($0)" + "($1)" }
// 15188888888
print(tel)
</pre>
split
根据分隔符将字符串变成数组
<pre>
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.characters.split(separator: " ")
.map(String.init))
// Prints "["BLANCHE:", "I", "don't", "want", "realism.", "I", "want", "magic!"]"
</pre>