在學(xué)習(xí)Swift 3的過(guò)程中整理了一些筆記,如果想看其他相關(guān)文章可前往《Swift 3必看》系列目錄
在之前的版本中,Swift中Error與OC中NSError的關(guān)系就像上海的南京路與南京的上海路關(guān)系一樣,那就是沒(méi)有關(guān)系。
我們先來(lái)看兩者的區(qū)別。
Error是一個(gè)實(shí)現(xiàn)ErrorProtocol枚舉,對(duì)外能夠獲取的具體信息只有rawValue。
enum HomeworkError : Int, Error {
case forgotten
case lost
case dogAteIt
}
但是我們知道NSError是有UserInfo和domain的:
throw NSError(code: HomeworkError.dogAteIt.rawValue,
domain: HomeworkError._domain,
userInfo: [ NSLocalizedDescriptionKey : "the dog ate it" ])
如果OC中的NSError橋接到Swift中,變成Error類型,那么獲取NSError中的UserInfo信息也變成了一件頭疼的事情,比如AVError:
catch let error as NSError where error._domain == AVFoundationErrorDomain
&& error._code == AVFoundationErrorDomain.diskFull.rawValue {
// okay: userInfo is finally accessible, but still weakly typed
}
很顯然,解決方式就是提供一個(gè)方式可以讓這兩個(gè)類型可以無(wú)損的轉(zhuǎn)換。
LocalizedError
增加了一個(gè)LocalizedError協(xié)議。這個(gè)協(xié)議增加了errorDescription屬性。如果Error同時(shí)實(shí)現(xiàn)這個(gè)協(xié)議,相比原來(lái)只有rawValue就增加了更多的信息。
extension HomeworkError : LocalizedError {
var errorDescription: String? {
switch self {
case .forgotten: return NSLocalizedString("I forgot it")
case .lost: return NSLocalizedString("I lost it")
case .dogAteIt: return NSLocalizedString("The dog ate it")
}
}
}
這個(gè)協(xié)議同時(shí)還有三個(gè)屬性:failureReason、helpAnchor、recoverySuggestion。
在NSError中也有對(duì)應(yīng)的三個(gè)屬性:
@property (readonly, copy) NSString *localizedDescription;
@property (nullable, readonly, copy) NSString *localizedFailureReason;
@property (nullable, readonly, copy) NSString *localizedRecoverySuggestion;
CustomNSError
CustomNSError 用來(lái)橋接原來(lái)NSError中的code、domain、UserInfo。
public protocol CustomNSError : Error {
/// The domain of the error.
public static var errorDomain: String { get }
/// The error code within the given domain.
public var errorCode: Int { get }
/// The user-info dictionary.
public var errorUserInfo: [String : Any] { get }
}
如果想讓我們的自定義Error可以轉(zhuǎn)成NSError,實(shí)現(xiàn)CustomNSError就可以完整的as成NSError。
RecoverableError
這次還給Error增加了RecoverableError協(xié)議。用來(lái)提示用戶可以通過(guò)什么樣的方式來(lái)處理這個(gè)Error。
歡迎關(guān)注我的微博:@沒(méi)故事的卓同學(xué)
相關(guān)鏈接:
SE-0112:Improved NSError Bridging