参考
Raw strings
SE-0200增加了 # 符号,使得写字符串更加简单。
-
在字符串中包含 " 时不必再加 \
//before let rain = "The \"rain\" in \"Spain\" falls mainly on the Spaniards." //after let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#
-
包含 \ 反斜杠也不需要再加转义符
// before let keypaths = "Swift keypaths such as \\Person.name hold uninvoked references to properties." // after let keypaths = #"Swift keypaths such as \Person.name hold uninvoked references to properties."#
由于反斜杠作为字符串中的字符,所以在插入值的时候需要在后面再加个 #
//before
let answer = 42
let dontpanic = "The answer to life, the universe, and everything is \(answer)"
// after
let answer = 42
let dontpanic = #"The answer to life, the universe, and everything is \#(answer)"#
-
当字符串包含 # 时, 前后应用 ## 包裹字符串
let str = ##"My dog said "woof"#gooddog"##
-
用 #""" 开头 """#结尾 来表示多行字符串
let multiline = #""" The answer to life, the universe, and everything is \#(answer). """#
-
由于不用反斜杠转义 使得正则表达式更加简洁明了
//before let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+" //after let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
Handling future enum cases
SE-0192 在枚举新增加一个 @unknown 修饰 default 分支,这样使得将来 enum 再增加一个 case 的时候,编译器会在该枚举的switch 代码里生成一个警告
比如
enum PasswordError: Error {
case short
case obvious
case simple
}
func showOld(error: PasswordError){
switch error {
case .short:
print("Your password was too short.")
case .obvious:
print("Your password was too obvious.")
default:
print("Your password was too simple.")
}
}
上面代码假如我们再加个 case old,执行代码时它会自动进入到default分支,可这并不是我们想要的结果,因为这个密码是一个旧密码而不是密码太简单,这时候可以用 @unknown,如下
enum PasswordError: Error {
case short
case obvious
case simple
case old
}
func showNew(error: PasswordError) {
switch error {
case .short:
print("Your password was too short.")
case .obvious:
print("Your password was too obvious.")
@unknown default:
print("Your password wasn't suitable.")
}
}
这时会产生一个警告 ,因为新增了case old ,switch没有明确地处理每一个分支。
Checking for integer muliples
SE-0225 integers 新增加了一个 isMultiple(of:) 方法
来检测一个数是否是另一个数的倍数
let rowNumber = 4
/*相当于 if rowNumber % 2 == 0
改成方法调用更易懂,更方便调用(有代码补全)
*/
if rowNumber.isMultiple(of:2) {
print("Even")
} else {
print("Odd")
}
Counting matching items in a sequence
SE-0220
Sequence 新增加了一个方法 count(where:) 相当于 filter() + count 的结果,但是它更加简洁一步到位
//before
let scores = [100,80,85]
let passCount = scores.filter{($0 >= 85)}.count
//after 避免生成一个数组
let scores = [100,80,85]
let passCount = scores.count { $0 >= 85}
这个方法适用于遵循了 Sequence 的所有类型,所以也可以用在 集合 和 字典里。
Transforming and unwrapping dictionary values with compactMapValues()
SE-0218 为字典新增了一个方法 compactMapValues(),正如数组的compactMap函数一样,可以过滤nil,类型转换
let times = [
"Hudson": "38",
"Clarke": "42",
"Robinson": "35",
"Hartis": "DNF"
]
//通过compactMapValues 将值转换成integer类型,并且将DNF过滤掉
let finishers1 = times.compactMapValues { Int($0) }
//也可以这样写
let finishers2 = times.compactMapValues(Int.init)
// 过滤nil
let people = [
"Paul": 38,
"Sophie": 8,
"Charlotte": 5,
"William": nil
]
let knownAges = people.compactMapValues { $0 }
结尾
Swift的每次更新都使得写起代码越来越简单高效。
附上一个网站 What's new in Swift