Raw strings
相關資料 SE-0200
原始字符串,說白了就是所見即所得,輸入的字符串長什么樣子,輸出的就長什么樣子(某些字符串插值的情況先不討論)
市面上大部分的編程語言,聲明使用字符串的時候用的都是引號""
,但是當字符串中出現(xiàn)""
的時候,字符串中的""
可能被當作該字符串的結(jié)束標志,從而導致奇奇怪怪的錯誤。
因此,先驅(qū)者們就引入了轉(zhuǎn)義字符\
(escape character),當字符串中需要某些特殊字符的時候,就需要在這些特殊字符前面加上轉(zhuǎn)義字符,方便編譯器對字符串進行處理。但是如果需要輸入轉(zhuǎn)義字符呢?那就需要在\
前面再加一個\
。這樣的字符串雖然可以讓編譯器識別,但是對于代碼的編寫者和閱讀者來說,過程還是有些痛苦的。
為了解決這個問題,Swift就引入了Raw string,使用方法是在你的字符串前后加上一個或多個#
號
let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#
可以看到,無論字符串中有多少""
都可以很好識別
有的人可能要問了,要是字符串中有"#
符號呢?注意了,我們前面說的是一個或多個
,沒錯,這時候我們需要做的只需要增加#
的數(shù)量的就行了,不過開頭和結(jié)尾的#
數(shù)量要保持一致
let str = ##"My dog said "woof"#gooddog"##
那我們的字符串插值怎么辦?加上一個#
即可
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我們就可以寫一些比較復雜的字符串了,特別是某些正則表達式,因為正則表達式中總是包含很多\
//before
let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
//now
let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
A standard Result type
相關資料 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)
}
最初見到這個類型是在Kingfisher開源庫中,第一次看到時感覺也沒什么,不就是新定義了一個Result枚舉,然后把success和failure包裝了起來,后來細細研究了一下,發(fā)現(xiàn)事情并沒有那么簡單。
Result提供了一個通用的范型,基本可以囊括所有的成功和失敗類型。也就是說,它對外提供了一個統(tǒng)一的結(jié)果類型,用來處理返回結(jié)果。
//eg
enum NetworkError: Error {
case badURL
}
//成功返回Int,錯誤返回NetworkError類型,用Result類型包裝起來
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é)果,標準的switch case來處理枚舉
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
方法,它會返回成功的結(jié)果,或者拋出錯誤結(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.")
}
}
另外,還提供了一種使用會拋出錯誤的closure來初始化Result類型的方法,該closure執(zhí)行后,成功的結(jié)果會被存儲在.success
中,拋出的錯誤會被存儲在.failure
public init(catching body: () throws -> Success) {
do {
self = .success(try body())
} catch {
self = .failure(error)
}
}
//eg
let result = Result { try String(contentsOfFile: someFile) }
其次,如果定義的錯誤類型不滿足需求的話,Result還提供了對結(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)." }
另一種情況是將上個結(jié)果的返回值轉(zhuǎn)換為另一個結(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)
//計算result2 .success結(jié)果的因子,然后返回另一個Result
let mapResult = result2.map { calculateFactors(for: $0) }
細心的朋友們可能會發(fā)現(xiàn),我們將.success轉(zhuǎn)換為另一個Result,也就是說mapResult的類型是Result<Result<Int, Factor>, Factor>
,而不是Result<Int, Factor>
,那如果結(jié)果需要轉(zhuǎn)換很多次呢?那豈不是要嵌套很多層?沒錯,很多朋友可能已經(jīng)想到了,那就是Swift中的flatMap
方法,Result也對其進行了實現(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)
}
}
//此時flatMapResult的類型為Result<Int, FactorError>
let flatMapResult = result2.flatMap { calculateFactors(for: $0) }
Customizing string interpolation
相關資料SE-0228
新的可自定義的字符串插值系統(tǒng),更加的高效靈活,增加了以前版本不可能實現(xiàn)的全新功能,它可以讓我們控制對象在字符串中的顯示方式。
//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
有人可能會說,直接實現(xiàn)CustomStringConvertible
不就行了,非得這么復雜,不僅需要擴展String.StringInterpolation
,還需要實現(xiàn)appendInterpolation
方法。沒錯,對于簡單的插值來說,重寫一下description
就行。
下面就來看一下,新的插值的全新特性。只要你開心,你可以自定義有很多個參數(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類型,需要注意一下幾點
- 需要遵循
ExpressibleByStringLiteral
,ExpressibleByStringInterpolation
,CustomStringConvertible
協(xié)議 - 在自定義類型中,需要創(chuàng)建一個
StringInterpolation
的結(jié)構體遵循StringInterpolationProtocol
- 實現(xiàn)
appendLiteral
方法,以及實現(xiàn)一個或多個appendInterpolation
方法 - 自定義類型需要有兩個初始化方法,允許直接從字符串,或字符串插值創(chuàng)建對象
//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>.
當然,它的玩法還有很多,需要我們慢慢探索。
Handling future enum cases
相關資料 SE-0192
處理未來可能改變的枚舉類型
Swift的安全特性需要switch
語句必須是詳盡的完全的,必須涵蓋所有的情況,但是將來添加新的case時,例如系統(tǒng)框架改變等,就會導致問題。
現(xiàn)在我們可以通過新增的@unknown
屬性來處理
- 對于所有其他case,應該運行此默認case,因為我不想單獨處理它們
- 我想單獨處理所有case,但如果將來出現(xiàn)任何case,請使用此選項,而不是導致錯誤
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
相關資料SE-0218
Dictionary
增加了compactMapValues()
方法,該方法將數(shù)組中的compactMap()
(轉(zhuǎn)換我的值,展開結(jié)果,放棄空值)與字典的mapValues()
(保持鍵不變,轉(zhuǎn)換我的值)結(jié)合起來。
//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 }
或者可以使用該方法拆包可選值,過濾nil
值,而不用做任何的類型轉(zhuǎn)換。
let people = [
"Paul": 38,
"Sophie": 8,
"Charlotte": 5,
"William": nil
]
let knownAges = people.compactMapValues { $0 }
Checking for integer multiples
相關資料SE-0225
新增isMultiple(of:)
方法,可是是我們更加清晰方便的判斷一個數(shù)是不是另一個數(shù)的倍數(shù),而不是每次都使用%
//判斷偶數(shù)
let rowNumber = 4
if rowNumber.isMultiple(of: 2) {
print("Even")
} else {
print("Odd")
}
Flattening nested optionals resulting from try?
相關資料SE-0230
修改了try?
的工作方式,讓嵌套的可選類型變成正常的可選類型,即讓多重可選值變成一重,這使得它的工作方式與可選鏈和條件類型轉(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
屬性,它將類型標記為可直接調(diào)用。
它是語法糖,而不是任何類型的編譯器魔法,將方法random(numberOfZeroes:3)
標記為@dynamicCallable
之后,可通過下面方式調(diào)用
random.dynamicallyCall(withKeywordArguments:["numberOfZeroes":3])
。
@dynamicCallable
是Swift 4.2的@dynamicMemberLookup
的擴展,為了使Swift代碼更容易與Python和JavaScript等動態(tài)語言一起工作。
要將此功能添加到您自己的類型,需要添加@dynamicCallable
屬性并實現(xiàn)下面方法
func dynamicCall(withArguments args: [Int]) -> Double
func dynamicCall(withKeywordArguments args: KeyValuePairs <String,Int>) -> Double
當你調(diào)用沒有參數(shù)標簽的類型(例如a(b,c))時會使用第一個,而當你提供標簽時使用第二個(例如a(b:cat,c:dog))。
@dynamicCallable
對于接受和返回的數(shù)據(jù)類型非常靈活,使您可以從Swift的所有類型安全性中受益,同時還有一些高級用途。因此,對于第一種方法(無參數(shù)標簽),您可以使用符合ExpressibleByArrayLiteral
的任何內(nèi)容,例如數(shù)組,數(shù)組切片和集合,對于第二種方法(使用參數(shù)標簽),您可以使用符合ExpressibleByDictionaryLiteral
的任何內(nèi)容,例如字典和鍵值對。
除了接受各種輸入外,您還可以為輸出提供多個重載,一個可能返回字符串,一個是整數(shù),依此類推。只要Swift能夠解決使用哪一個,你就可以混合搭配你想要的一切。
我們來看一個例子。這是一個生成介于0和某個最大值之間數(shù)字的結(jié)構,具體取決于傳入的輸入:
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)用該方法,或者為零,因此讀取第一個值并為其設置默認值。
我們現(xiàn)在可以創(chuàng)建一個RandomNumberGenerator1實例并像函數(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時需要注意:
- 可以將它應用于結(jié)構,枚舉,類和協(xié)議
- 如果你實現(xiàn)
withKeywordArguments:
并且沒有實現(xiàn)withArguments:
,你的類型仍然可以在沒有參數(shù)標簽的情況下調(diào)用,你只需要將鍵設置為空字符串就行 - 如果
withKeywordArguments:
或withArguments:
被標記為throw,則調(diào)用該類型也會throw - 您不能將
@dynamicCallable
添加到擴展,只能添加在類型的主要定義中 - 可以為類型添加其他方法和屬性,并正常使用它們。
另外,它不支持方法解析,這意味著我們必須直接調(diào)用類型(例如random(numberOfZeroes: 5),而不是調(diào)用類型上的特定方法(例如random.generate(numberOfZeroes: 5)