简介:
Swift发布后提供了很多高效的标准库函数,其实早在 Swift 正式发布之前,iOS / Cocoa 开发者都可以使用诸如 ObjectiveSugar 或者 ReactiveCocoa 第三方库,实现类似 map、flatMap 或 filter 等函数式编程的构建。
并且通过使用函数式编程能够更好地表达你的意图,减少代码的行数,以及使用链式结构构建复杂的逻辑,更显清爽。
接下来,介绍一下常用的一些标准库函数:
1.在文档中提到的库函数(The Swift Programming Language)
//断言,参数如果为true则继续,否则抛出异常
assert(true)
//swift 1.0 计算序列的元素个数
let str = "sk87v5"
countElements("str") == 6
//swift2.0后计算字符串长度
print(str.characters.count)//6
//swift2.0后计算数组元素
let arr = ["sk", "wyj", "jj"]
print(arr.count)//3
//返回一个新的序列,其中每个元素是一个元组,第一个值为原来元素所在的位置index,第二个为原来序列中的元素
let array = ["N", "B","A"]
for (i, j) in array.enumerate() {
print("\(i):\(j)")
}
打印结果:
//0:N
//1:B
//2:A
//返回所有参数中的最小值
min(9, 2, 4) == 2
//打印
print("Hello")
//Swift1.0 使用的打印 (带换行)
// println mentioned on page 4
println("World")
//排序
// sort mentioned on page 14
let array = ["N", "B","A"]
for i in array.sort() {
print(i) // A B N
}
2.文档未提的实用函数
- Swift 1.0
- map(sequence, transformClosure):对数组中每个元素都执行闭包,并将所有闭包的结果合成一个新数组并返回。
- Swift 2.0
- map(transform: (Int) throws -> T):对数组中每个元素都执行闭包中的操作,并将所有闭包的结果合成一个新序列数组并返回。
//swift 2.0
let array = [1, 10, 22, 40, 88, 90, 99]
//1.常规用法
let newArr = array.map { (a : Int) -> Int in
return a + 10
}
print(newArr)
//2.简化用法
let newArr = array.map({$0 + 10})
print(newArr)
//打印结果:
[11, 20, 32, 50, 98, 100, 109]
- (Swift 1.0)
- filter(sequence, includeElementClosure):
- (Swift 2.0)
- filter(includeElement: (Int) throws -> Bool)
对序列数组中每个元素都执行includeElement闭包,并将所有闭包结果为true的元素合成一个新数组并返回。
//swift 2.0
let array = [1, 10, 22, 40, 88, 90, 99]
//1.常规用法
let newArr = array.filter { (a : Int) -> Bool in
return a % 10 == 0
}
print(newArr)//[10, 40, 90]\n
//2.简化用法
let newArr = array.filter({$0 % 10 == 0})
print(newArr)//[10, 40, 90]\n
- Swift 1.0
- reduce(sequence, initial, combineClosure):给定一个数组sequence,以及一个初始值initial,然后将initial和数组里的第1个元素作为参数传入combineClosure闭包中进行运算,得到的结果保存到initial;然后再将initial和第2个元素传入combineClosure闭包中计算,结果保存到initial;重复计算直到所有sequence中的元素都计算完毕,并返回最终的initial值。
- Swift 2.0
- reduce(initial: T, combine: (T, String) throws -> T)
//1.传统求和
let arrNum = [1, 2, 3, 4 ,5]
var sum = 0
for num in arrNum {
sum = sum + num
}
print(sum) //15
//2.传统求积
var a = 1
for num in arrNum {
a = a * num
}
print(a)//120
//2.reduce求和,求积:
let arrNum = [1, 2, 3, 4, 5]
//简化一:
let sum = arrNum.reduce(0, combine: {$0 + $1})
let a = arrNum.reduce(1, combine: {$0 * $1})
//简化二:
//初始值 initial 为 0,每次遍历数组元素,执行 + 操作
let sum = arrNum.reduce(0, combine: +)
//初始值 initial 为 1,每次遍历数组元素,执行 * 操作
let a = arrNum.reduce(1, combine: *)
print(sum)
print(a)
let arr = ["sk", "wyj", "jj", "dyf", "zjz"]
let arrNew = arr.reduce("87v5", combine: + )
print(arrNew)
- abs(signedNumber):返回数字的绝对值
abs(-1) == 1 //true
abs(-42) == 42 //true
abs(42) == 42 //true
- contains(sequence, element):
- 如果某个序列
sequence
(比如说一个数组)包含指定的元素element
,则返回true
,否则返回false
。
let arr = ["sk", "wyj", "jj", "dyf", "zjz"]
arr.contains("sk")// true
arr.contains("87v5")// false
- dropFirst(sequence):
- 返回一个去掉了首个元素的、新的序列(比如一个新数组)。
let array = ["xmg", "sk", "why"]
var arrayNew = array.dropFirst() //["sk", "why"]
//去掉前2个元素
var arrayNewTwo = array.dropFirst(2) //["why"]
//注:elementsEqual() iOS9.0后可用
arrayNew.elementsEqual(array) //false
- dropLast(sequence):返回一个去掉了最后一个元素的、新的序列(比如一个新数组)。
let array = ["xmg", "sk", "why"]
var arrayNew = array.dropLast() //["xmg", "sk"]
//去掉后2个元素
var arrayNewTwo = array.dropLast(2) //["xmg"]
arrayNew.elementsEqual(["xmg", "sk"]) //true
- dump(object):打印出某个对象object的所有信息
let array = ["xmg", "sk", "why"]
dump(array) //["xmg", "sk", "why"]
// Prints:
//3 elements
//- [0]: xmg
//- [1]: sk
//- [2]: why
//注:dump和print的区别:dump打印的是内容,print打印的是内容+ 换行符的字符串
print(array)//"["xmg", "sk", "why"]\n"
- elementsEqual():判断两个序列是否相等
let array = ["xmg", "sk", "why"]
array.elementsEqual(["sk"]) //false
let arrayOne = array.dropLast()
let arrayTwo = ["xmg", "sk"]
arrayOne.elementsEqual(arrayTwo) //true
- (Swift1.0)
- find(sequence, element):返回序列sequence中某元素element的位置index。如果序列中不存在此元素,则返回nil。
- (Swift2.0)
- arr.indexOf(element: String):返回数组中某元素element的位置index。如果数组中不存在此元素,则返回nil
//find(sequence, element)
let arr = ["sk", "wyj", "jj"]
find(arr, "sk") == 0
find(arr, "dyf") == nil
find([29, 85, 42, 96, 75], 42) == 2
//indexOf(element: String)
let arr = ["sk", "wyj", "jj"]
let index = arr.indexOf("sk") //0
let index2 = arr.indexOf("dyf")//nil
- (Swift 1.0)
- indices(sequence):返回序列sequence中所有元素的位置(indices是index的复数)
- (Swift 2.0)
- 改为属性indices,返回Range类型
//swift1.0
equal(indices([29, 85, 42]), [0, 1, 2])
for i in indices([29, 85, 42]) {
// 0, 1, 2
print(i)
}
//swift2.0
let arr = ["sk", "wyj", "jj"]
let a = arr.indices
print(a) //0..<3
- (Swift1.0)
- join(separator, sequence):将序列sequence通过分隔符separator连成一个字符串,并返回此字符串。
- (Swift2.0)
- joinWithSeparator(separator: String)
//swift1.0
join(":", ["A", "B", "C"]) == "A:B:C"
let arr = ["sk", "wyj", "jj"]
join("/", arr) == "sk/wyj/jj"
//swift2.0
let arr = ["sk", "wyj", "jj"]
let joinArr = arr.joinWithSeparator("/")
print(joinArr)
打印结果:
sk/wyj/jj
- max(comparable1, comparable2, etc.):返回参数中的最大值。
max(0, 1) == 1
max(8, 2, 3) == 8
- maxElement(sequence):返回序列sequence中的最大值。
//swift 1.0
let array = [1, 10, 22, 40, 88, 90, 99]
maxElement(array) //99
//swift 2.0
let array = [1, 10, 22, 40, 88, 90, 99]
array.maxElement() //99
- minElements(sequence):返回序列sequence中的最小值。
//swift 1.0
let array = [1, 10, 22, 40, 88, 90, 99]
minElement(array) //1
//swift 2.0
let array = [1, 10, 22, 40, 88, 90, 99]
array.minElement() //1
- reverse(sequence):返回逆序的序列sequence。
let array = [1, 10, 22, 40, 88, 90, 99]
for i in array.reverse() {
print(i)
}
- Swift 1.0
- startsWith(sequence1, sequence2):如果序列sequence1中开头的元素跟序列sequence2中的所有元素都相等,则返回true,否则返回false。
- Swift 2.0
- startsWith(other: SequenceType)
//swift 1.0
startsWith(1..20, 1..5) == true
let arr1 = ["sk", "wyj", "jj"]
let arr2 = ["sk"]
startsWith(arr1, arr2) == true
//swift 2.0
let range1 = 1..<20
let range2 = 1..<5
if range1.startsWith(range2) {
print("range2所有元素和range1开头元素相等")
}else {
print("不相等")
}
let arr1 = ["sk", "wyj", "jj"]
let arr2 = ["sk"]
if arr1.startsWith(arr2) {
print("arr2所有元素和arr1开头所有元素相等")
}else {
print("不相等")
}
附:Swift1.0 中74个内置函数:
abs(...)
advance(...)
alignof(...)
alignofValue(...)
assert(...)
bridgeFromObjectiveC(...)
bridgeFromObjectiveCUnconditional(...)
bridgeToObjectiveC(...)
bridgeToObjectiveCUnconditional(...)
c_malloc_size(...)
c_memcpy(...)
c_putchar(...)
contains(...)
count(...)
countElements(...)
countLeadingZeros(...)
debugPrint(...)
debugPrintln(...)
distance(...)
dropFirst(...)
dropLast(...)
dump(...)
encodeBitsAsWords(...)
enumerate(...)
equal(...)
filter(...)
find(...)
getBridgedObjectiveCType(...)
getVaList(...)
indices(...)
insertionSort(...)
isBridgedToObjectiveC(...)
isBridgedVerbatimToObjectiveC(...)
isUniquelyReferenced(...)
join(...)
lexicographicalCompare(...)
map(...)
max(...)
maxElement(...)
min(...)
minElement(...)
numericCast(...)
partition(...)
posix_read(...)
posix_write(...)
print(...)
println(...)
quickSort(...)
reduce(...)
reflect(...)
reinterpretCast(...)
reverse(...)
roundUpToAlignment(...)
sizeof(...)
sizeofValue(...)
sort(...)
split(...)
startsWith(...)
strideof(...)
strideofValue(...)
swap(...)
swift_MagicMirrorData_summaryImpl(...)
swift_bufferAllocate(...)
swift_keepAlive(...)
toString(...)
transcode(...)
underestimateCount(...)
unsafeReflect(...)
withExtendedLifetime(...)
withObjectAtPlusZero(...)
withUnsafePointer(...)
withUnsafePointerToObject(...)
withUnsafePointers(...)
withVaList(...)
codeStraight原创文章,如有错误,欢迎指正!
http://www.jianshu.com/p/2c7407c76ad8