Raw strings
相關(guān)資料 SE-0200
原始字符串吓笙,說(shuō)白了就是所見(jiàn)即所得面睛,輸入的字符串長(zhǎng)什么樣子尊搬,輸出的就長(zhǎng)什么樣子(某些字符串插值的情況先不討論)
市面上大部分的編程語(yǔ)言佛寿,聲明使用字符串的時(shí)候用的都是引號(hào)""
冀泻,但是當(dāng)字符串中出現(xiàn)""
的時(shí)候弹渔,字符串中的""
可能被當(dāng)作該字符串的結(jié)束標(biāo)志肢专,從而導(dǎo)致奇奇怪怪的錯(cuò)誤。
因此胆绊,先驅(qū)者們就引入了轉(zhuǎn)義字符\
(escape character)压状,當(dāng)字符串中需要某些特殊字符的時(shí)候种冬,就需要在這些特殊字符前面加上轉(zhuǎn)義字符娱两,方便編譯器對(duì)字符串進(jìn)行處理。但是如果需要輸入轉(zhuǎn)義字符呢趣竣?那就需要在\
前面再加一個(gè)\
遥缕。這樣的字符串雖然可以讓編譯器識(shí)別单匣,但是對(duì)于代碼的編寫(xiě)者和閱讀者來(lái)說(shuō)户秤,過(guò)程還是有些痛苦的虎忌。
為了解決這個(gè)問(wèn)題膜蠢,Swift就引入了Raw string挑围,使用方法是在你的字符串前后加上一個(gè)或多個(gè)#
號(hào)
let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#
可以看到杉辙,無(wú)論字符串中有多少""
都可以很好識(shí)別
有的人可能要問(wèn)了蜘矢,要是字符串中有"#
符號(hào)呢品腹?注意了舞吭,我們前面說(shuō)的是一個(gè)或多個(gè)
羡鸥,沒(méi)錯(cuò)惧浴,這時(shí)候我們需要做的只需要增加#
的數(shù)量的就行了衷旅,不過(guò)開(kāi)頭和結(jié)尾的#
數(shù)量要保持一致
let str = ##"My dog said "woof"#gooddog"##
那我們的字符串插值怎么辦芜茵?加上一個(gè)#
即可
let answer = 42
//before
let dontpanic = "The answer is \(answer)."
//now
let dontpanic = #"The answer is \#(answer)."#
同樣的Raw strings也支持Swift的多行字符串
let multiline = #"""
The answer to life,
the universe,
and everything is \#(answer).
"""#
有了Raw string我們就可以寫(xiě)一些比較復(fù)雜的字符串了,特別是某些正則表達(dá)式猪钮,因?yàn)檎齽t表達(dá)式中總是包含很多\
//before
let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
//now
let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
A standard Result type
相關(guān)資料 SE-0235
public enum Result<Success, Failure> where Failure : Error {
case success(Success)
case failure(Failure)
public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> Result<NewSuccess, Failure>
public func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> Result<Success, NewFailure> where NewFailure : Error
public func flatMap<NewSuccess>(_ transform: (Success) -> Result<NewSuccess, Failure>) -> Result<NewSuccess, Failure>
public func flatMapError<NewFailure>(_ transform: (Failure) -> Result<Success, NewFailure>) -> Result<Success, NewFailure> where NewFailure : Error
public func get() throws -> Success
public init(catching body: () throws -> Success)
}
最初見(jiàn)到這個(gè)類(lèi)型是在Kingfisher開(kāi)源庫(kù)中烤低,第一次看到時(shí)感覺(jué)也沒(méi)什么扑馁,不就是新定義了一個(gè)Result枚舉腻要,然后把success和failure包裝了起來(lái)雄家,后來(lái)細(xì)細(xì)研究了一下趟济,發(fā)現(xiàn)事情并沒(méi)有那么簡(jiǎn)單。
Result提供了一個(gè)通用的范型勾效,基本可以囊括所有的成功和失敗類(lèi)型层宫。也就是說(shuō)萌腿,它對(duì)外提供了一個(gè)統(tǒng)一的結(jié)果類(lèi)型毁菱,用來(lái)處理返回結(jié)果。
//eg
enum NetworkError: Error {
case badURL
}
//成功返回Int贮庞,錯(cuò)誤返回NetworkError類(lèi)型窗慎,用Result類(lèi)型包裝起來(lái)
func fetchUnreadCount1(from urlString: String, completionHandler: @escaping (Result<Int, NetworkError>) -> Void) {
guard let url = URL(string: urlString) else {
completionHandler(.failure(.badURL))
return
}
// complicated networking code here
print("Fetching \(url.absoluteString)...")
completionHandler(.success(5))
}
//處理返回結(jié)果峦失,標(biāo)準(zhǔn)的switch case來(lái)處理枚舉
fetchUnreadCount1(from: "https://www.hackingwithswift.com") { result in
switch result {
case .success(let count):
print("\(count) unread messages.")
case .failure(let error):
print(error.localizedDescription)
}
}
Result提供了get
方法,它會(huì)返回成功的結(jié)果隧魄,或者拋出錯(cuò)誤結(jié)果。
//get方法
public func get() throws -> Success {
switch self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
fetchUnreadCount1(from: "https://www.hackingwithswift.com") { result in
if let count = try? result.get() {
print("\(count) unread messages.")
}
}
另外,還提供了一種使用會(huì)拋出錯(cuò)誤的closure來(lái)初始化Result類(lèi)型的方法辉川,該closure執(zhí)行后乓旗,成功的結(jié)果會(huì)被存儲(chǔ)在.success
中汇跨,拋出的錯(cuò)誤會(huì)被存儲(chǔ)在.failure
public init(catching body: () throws -> Success) {
do {
self = .success(try body())
} catch {
self = .failure(error)
}
}
//eg
let result = Result { try String(contentsOfFile: someFile) }
其次,如果定義的錯(cuò)誤類(lèi)型不滿(mǎn)足需求的話(huà)蚪黑,Result還提供了對(duì)結(jié)果的轉(zhuǎn)換方法,map(), flatMap(), mapError(), flatMapError()
enum FactorError: Error {
case belowMinimum
case isPrime
}
func generateRandomNumber(maximum: Int) -> Result<Int, FactorError> {
if maximum < 0 {
// creating a range below 0 will crash, so refuse
return .failure(.belowMinimum)
} else {
let number = Int.random(in: 0...maximum)
return .success(number)
}
}
let result1 = generateRandomNumber(maximum: 11)
//如果result1是.success,下面的map方法, 將
//Result<Int, FactorError>轉(zhuǎn)換為Result<String, FatorError>
//如果是.failure动分,不做處理姆另,僅僅將failure返回
let stringNumber = result1.map { "The random number is: \($0)." }
另一種情況是將上個(gè)結(jié)果的返回值轉(zhuǎn)換為另一個(gè)結(jié)果
func calculateFactors(for number: Int) -> Result<Int, FactorError> {
let factors = (1...number).filter { number % $0 == 0 }
if factors.count == 2 {
return .failure(.isPrime)
} else {
return .success(factors.count)
}
}
let result2 = generateRandomNumber(maximum: 10)
//計(jì)算result2 .success結(jié)果的因子蝶防,然后返回另一個(gè)Result
let mapResult = result2.map { calculateFactors(for: $0) }
細(xì)心的朋友們可能會(huì)發(fā)現(xiàn),我們將.success轉(zhuǎn)換為另一個(gè)Result,也就是說(shuō)mapResult的類(lèi)型是Result<Result<Int, Factor>, Factor>
嘿悬,而不是Result<Int, Factor>
窒盐,那如果結(jié)果需要轉(zhuǎn)換很多次呢?那豈不是要嵌套很多層?沒(méi)錯(cuò)塔鳍,很多朋友可能已經(jīng)想到了,那就是Swift中的flatMap
方法,Result也對(duì)其進(jìn)行了實(shí)現(xiàn)
public func flatMap<NewSuccess>(_ transform: (Success) -> Result<NewSuccess, Failure>) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
public func flatMapError<NewFailure>(_ transform: (Failure) -> Result<Success, NewFailure>) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}
//此時(shí)flatMapResult的類(lèi)型為Result<Int, FactorError>
let flatMapResult = result2.flatMap { calculateFactors(for: $0) }
Customizing string interpolation
相關(guān)資料SE-0228
新的可自定義的字符串插值系統(tǒng)葱她,更加的高效靈活搓谆,增加了以前版本不可能實(shí)現(xiàn)的全新功能,它可以讓我們控制對(duì)象在字符串中的顯示方式斩萌。
//eg
struct User {
var name: String
var age: Int
}
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: User) {
appendInterpolation("My name is \(value.name) and I'm \(value.age)")
}
}
let user = User(name: "Sunshine", age: 18)
print("User details: \(user)")
//before: User(name: "Sunshine", age: 18)
//after: My name is Sunshine and I'm 18
有人可能會(huì)說(shuō)亭枷,直接實(shí)現(xiàn)CustomStringConvertible
不就行了瘤睹,非得這么復(fù)雜,不僅需要擴(kuò)展String.StringInterpolation
获茬,還需要實(shí)現(xiàn)appendInterpolation
方法渤涌。沒(méi)錯(cuò)茸俭,對(duì)于簡(jiǎn)單的插值來(lái)說(shuō)酌伊,重寫(xiě)一下description
就行燕锥。
下面就來(lái)看一下鼻由,新的插值的全新特性。只要你開(kāi)心,你可以自定義有很多個(gè)參數(shù)的插值方法查吊。
extensionn String.StringInterpolation {
mutating func appendInterpolation(_ number: Int, style: NumberFormatter.Style) {
let formatter = NumberFormatter()
formatter.numberStyle = style
if let result = formatter.string(from: number as NSNumber) {
appendLiteral(result)
}
}
mutating func appendInterpolation(repeat str: String, _ count: Int) {
for _ in 0 ..< count {
appendLiteral(str)
}
}
mutating func appendInterpolation(_ values: [String], empty defaultValue: @autoclosure () -> String) {
if values.count == 0 {
appendLiteral(defaultValue())
} else {
appendLiteral(values.joined(separator: ", "))
}
}
}
//we can use like this
print("The lucky number is \(8, style: .spellOut)")
//res: The lucky number is eight.
print("This T-shirt is \(repeat: "buling", 2)")
//res: This T-shirt is buling buling
let nums = ["1", "2", "3"]
print("List of nums: \(nums, empty: "No one").")
//res: List of nums: 1, 2, 3.
我們也可以定義自己的interpolation類(lèi)型,需要注意一下幾點(diǎn)
- 需要遵循
ExpressibleByStringLiteral
,ExpressibleByStringInterpolation
,CustomStringConvertible
協(xié)議 - 在自定義類(lèi)型中,需要?jiǎng)?chuàng)建一個(gè)
StringInterpolation
的結(jié)構(gòu)體遵循StringInterpolationProtocol
- 實(shí)現(xiàn)
appendLiteral
方法,以及實(shí)現(xiàn)一個(gè)或多個(gè)appendInterpolation
方法 - 自定義類(lèi)型需要有兩個(gè)初始化方法,允許直接從字符串,或字符串插值創(chuàng)建對(duì)象
//copy from Whats-New-In-Swift-5-0
struct HTMLComponent: ExpressibleByStringLiteral, ExpressibleByStringInterpolation, CustomStringConvertible {
struct StringInterpolation: StringInterpolationProtocol {
// start with an empty string
var output = ""
// allocate enough space to hold twice the amount of literal text
init(literalCapacity: Int, interpolationCount: Int) {
output.reserveCapacity(literalCapacity * 2)
}
// a hard-coded piece of text – just add it
mutating func appendLiteral(_ literal: String) {
print("Appending \(literal)")
output.append(literal)
}
// a Twitter username – add it as a link
mutating func appendInterpolation(twitter: String) {
print("Appending \(twitter)")
output.append("<a href=\"https://twitter/\(twitter)\">@\(twitter)</a>")
}
// an email address – add it using mailto
mutating func appendInterpolation(email: String) {
print("Appending \(email)")
output.append("<a href=\"mailto:\(email)\">\(email)</a>")
}
}
// the finished text for this whole component
let description: String
// create an instance from a literal string
init(stringLiteral value: String) {
description = value
}
// create an instance from an interpolated string
init(stringInterpolation: StringInterpolation) {
description = stringInterpolation.output
}
}
//usage
let text: HTMLComponent = "You should follow me on Twitter \(twitter: "twostraws"), or you can email me at \(email: "paul@hackingwithswift.com")."
//You should follow me on Twitter <a href="https://twitter/twostraws">@twostraws</a>, or you can email me at <a href="mailto:paul@hackingwithswift.com">paul@hackingwithswift.com</a>.
當(dāng)然,它的玩法還有很多,需要我們慢慢探索。
Handling future enum cases
相關(guān)資料 SE-0192
處理未來(lái)可能改變的枚舉類(lèi)型
Swift的安全特性需要switch
語(yǔ)句必須是詳盡的完全的,必須涵蓋所有的情況徙瓶,但是將來(lái)添加新的case時(shí)澎埠,例如系統(tǒng)框架改變等,就會(huì)導(dǎo)致問(wèn)題。
現(xiàn)在我們可以通過(guò)新增的@unknown
屬性來(lái)處理
- 對(duì)于所有其他case晾腔,應(yīng)該運(yùn)行此默認(rèn)case,因?yàn)槲也幌雴为?dú)處理它們
- 我想單獨(dú)處理所有case,但如果將來(lái)出現(xiàn)任何case,請(qǐng)使用此選項(xiàng),而不是導(dǎo)致錯(cuò)誤
enum PasswordError: Error {
case short
case obvious
case simple
}
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.")
}
}
//cause warning: Switch must be exhaustive.
Transforming and unwrapping dictionary values
相關(guān)資料SE-0218
Dictionary
增加了compactMapValues()
方法,該方法將數(shù)組中的compactMap()
(轉(zhuǎn)換我的值,展開(kāi)結(jié)果,放棄空值)與字典的mapValues()
(保持鍵不變晚树,轉(zhuǎn)換我的值)結(jié)合起來(lái)宝鼓。
//eg
//返回value是Int的新字典
let times = [
"Hudson": "38",
"Clarke": "42",
"Robinson": "35",
"Hartis": "DNF"
]
//two ways
let finishers1 = times.compactMapValues { Int($0) }
let finishers2 = times.compactMapValues { Init.init }
或者可以使用該方法拆包可選值,過(guò)濾nil
值胡陪,而不用做任何的類(lèi)型轉(zhuǎn)換沥寥。
let people = [
"Paul": 38,
"Sophie": 8,
"Charlotte": 5,
"William": nil
]
let knownAges = people.compactMapValues { $0 }
Checking for integer multiples
相關(guān)資料SE-0225
新增isMultiple(of:)
方法,可是是我們更加清晰方便的判斷一個(gè)數(shù)是不是另一個(gè)數(shù)的倍數(shù)柠座,而不是每次都使用%
//判斷偶數(shù)
let rowNumber = 4
if rowNumber.isMultiple(of: 2) {
print("Even")
} else {
print("Odd")
}
Flattening nested optionals resulting from try?
相關(guān)資料SE-0230
修改了try?
的工作方式营曼,讓嵌套的可選類(lèi)型變成正常的可選類(lèi)型,即讓多重可選值變成一重愚隧,這使得它的工作方式與可選鏈和條件類(lèi)型轉(zhuǎn)換相同蒂阱。
struct User {
var id: Int
init?(id: Int) {
if id < 1 {
return nil
}
self.id = id
}
func getMessages() throws -> String {
// complicated code here
return "No messages"
}
}
let user = User(id: 1)
let messages = try? user?.getMessages()
//before swift 5.0: String?? 即Optional(Optional(String))
//now: String? 即Optional(String)
Dynamically callable types
SE-0216
增加了@dynamicCallable
屬性,它將類(lèi)型標(biāo)記為可直接調(diào)用狂塘。
它是語(yǔ)法糖录煤,而不是任何類(lèi)型的編譯器魔法,將方法random(numberOfZeroes:3)
標(biāo)記為@dynamicCallable
之后荞胡,可通過(guò)下面方式調(diào)用
random.dynamicallyCall(withKeywordArguments:["numberOfZeroes":3])
妈踊。
@dynamicCallable
是Swift 4.2的@dynamicMemberLookup
的擴(kuò)展,為了使Swift代碼更容易與Python和JavaScript等動(dòng)態(tài)語(yǔ)言一起工作泪漂。
要將此功能添加到您自己的類(lèi)型廊营,需要添加@dynamicCallable
屬性并實(shí)現(xiàn)下面方法
func dynamicCall(withArguments args: [Int]) -> Double
func dynamicCall(withKeywordArguments args: KeyValuePairs <String,Int>) -> Double
當(dāng)你調(diào)用沒(méi)有參數(shù)標(biāo)簽的類(lèi)型(例如a(b萝勤,c))時(shí)會(huì)使用第一個(gè)露筒,而當(dāng)你提供標(biāo)簽時(shí)使用第二個(gè)(例如a(b:cat,c:dog))敌卓。
@dynamicCallable
對(duì)于接受和返回的數(shù)據(jù)類(lèi)型非常靈活慎式,使您可以從Swift的所有類(lèi)型安全性中受益,同時(shí)還有一些高級(jí)用途。因此瘪吏,對(duì)于第一種方法(無(wú)參數(shù)標(biāo)簽)癣防,您可以使用符合ExpressibleByArrayLiteral
的任何內(nèi)容,例如數(shù)組掌眠,數(shù)組切片和集合蕾盯,對(duì)于第二種方法(使用參數(shù)標(biāo)簽),您可以使用符合ExpressibleByDictionaryLiteral
的任何內(nèi)容蓝丙,例如字典和鍵值對(duì)级遭。
除了接受各種輸入外,您還可以為輸出提供多個(gè)重載迅腔,一個(gè)可能返回字符串装畅,一個(gè)是整數(shù),依此類(lèi)推沧烈。只要Swift能夠解決使用哪一個(gè)掠兄,你就可以混合搭配你想要的一切。
我們來(lái)看一個(gè)例子锌雀。這是一個(gè)生成介于0和某個(gè)最大值之間數(shù)字的結(jié)構(gòu)蚂夕,具體取決于傳入的輸入:
import Foundation
@dynamicCallable
struct RandomNumberGenerator1 {
func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Double {
let numberOfZeroes = Double(args.first?.value ?? 0)
let maximum = pow(10, numberOfZeroes)
return Double.random(in: 0...maximum)
}
}
可以使用任意數(shù)量的參數(shù)調(diào)用該方法,或者為零腋逆,因此讀取第一個(gè)值并為其設(shè)置默認(rèn)值婿牍。
我們現(xiàn)在可以創(chuàng)建一個(gè)RandomNumberGenerator1實(shí)例并像函數(shù)一樣調(diào)用:
let random1 = RandomNumberGenerator1()
let result1 = random1(numberOfZeroes: 0)
或者
@dynamicCallable
struct RandomNumberGenerator2 {
func dynamicallyCall(withArguments args: [Int]) -> Double {
let numberOfZeroes = Double(args[0])
let maximum = pow(10, numberOfZeroes)
return Double.random(in: 0...maximum)
}
}
let random2 = RandomNumberGenerator2()
let result2 = random2(0)
使用@dynamicCallable時(shí)需要注意:
- 可以將它應(yīng)用于結(jié)構(gòu),枚舉惩歉,類(lèi)和協(xié)議
- 如果你實(shí)現(xiàn)
withKeywordArguments:
并且沒(méi)有實(shí)現(xiàn)withArguments:
等脂,你的類(lèi)型仍然可以在沒(méi)有參數(shù)標(biāo)簽的情況下調(diào)用,你只需要將鍵設(shè)置為空字符串就行 - 如果
withKeywordArguments:
或withArguments:
被標(biāo)記為throw撑蚌,則調(diào)用該類(lèi)型也會(huì)throw - 您不能將
@dynamicCallable
添加到擴(kuò)展上遥,只能添加在類(lèi)型的主要定義中 - 可以為類(lèi)型添加其他方法和屬性,并正常使用它們争涌。
另外粉楚,它不支持方法解析,這意味著我們必須直接調(diào)用類(lèi)型(例如random(numberOfZeroes: 5)亮垫,而不是調(diào)用類(lèi)型上的特定方法(例如random.generate(numberOfZeroes: 5)