本小节主要对下面两个demo的统一抽象封装引出来的一些思路。
1.查看某一系列文件的有效性
2.看一个数字数组中所有数字是不是都不是质数
因为检查是不是质数不会报错,而检查文件可能会throws异常,从而引出rethrows
关键字。
检查一个文件的有效性checkFile方法应该有三种情况,有效
,无效
,检查出错
Demo中 用一个for循环确认每一个文件的有效性,遇到无效文件或者检查出错都会提前退出循环
。
///检查文件有效性的方法
func checkFile(filename: String) throws -> Bool
func checkAllFiles(filenames: [String]) throws -> Bool {
for filename in filenames {
guard try checkFile(filename: filename) else { return false } }
return true
}
func checkPrimes(_ numbers: [Int]) -> Bool {
for number in numbers {
guard number.isPrime else { return false }
}
return true
}
checkPrimes([2,3,7,17]) // true
checkPrimes([2,3,4,5]) // false
extension Sequence {
/// Returns `true` iff all elements satisfy the predicate
func all(condition: (Iterator.Element) -> Bool) -> Bool {
for element in self {
guard condition(element) else { return false }
}
return true
}
}
func checkPrimes2(_ numbers: [Int]) -> Bool {
return numbers.all { $0.isPrime }
}
extension Sequence {
func all(condition: (Iterator.Element) throws -> Bool) rethrows
-> Bool {
for element in self {
guard try condition(element) else { return false }
}
return true
}
}
上面检查质数的Demo不受影响,而且检查文件有效性就可以像下面这样写了
///有try了
func checkAllFiles(filenames: [String]) throws -> Bool {
return try filenames.all(condition: checkFile)
}
知识点:标准库中序列和集合几乎所有可以接收函数做参数的函数
都被标记成rethrows了。 这样做就很稳了~
over~