CustomDebugStringConvertible
//standard description
public protocol CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
///
/// Calling this property directly is discouraged. Instead, convert an
/// instance of any type to a string by using the `String(reflecting:)`
/// initializer. This initializer works with any type, and uses the custom
/// `debugDescription` property for types that conform to
/// `CustomDebugStringConvertible`:
///
/// struct Point: CustomDebugStringConvertible {
/// let x: Int, y: Int
///
/// var debugDescription: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(reflecting: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `debugDescription` property.
public var debugDescription: String { get }
}
//使用例子 這里借鑒的是PromiseKit 框架的源碼
extension PMKError: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .flatMap(let obj, let type):
return "Could not `flatMap<\(type)>`: \(obj)"
case .compactMap(let obj, let type):
return "Could not `compactMap<\(type)>`: \(obj)"
case .invalidCallingConvention:
return "A closure was called with an invalid calling convention, probably (nil, nil)"
case .returnedSelf:
return "A promise handler returned itself"
case .badInput:
return "Bad input was provided to a PromiseKit function"
case .cancelled:
return "The asynchronous sequence was cancelled"
case .emptySequence:
return "The first or last element was requested for an empty sequence"
}
}
}
LocalizedError
/// Describes an error that provides localized messages describing why
/// an error occurred and provides more information about the error.
public protocol LocalizedError : Error {
/// A localized message describing what error occurred.
public var errorDescription: String? { get }
/// A localized message describing the reason for the failure.
public var failureReason: String? { get }
/// A localized message describing how one might recover from the failure.
public var recoverySuggestion: String? { get }
/// A localized message providing "help" text if the user requests help.
public var helpAnchor: String? { get }
}
//Usage(用法)
extension PMKError: LocalizedError {
public var errorDescription: String? {
return debugDescription
}
}
總結:
- 什么情況下使用客蹋?
當我們寫一個框架的時候碰逸,我們自定義一個錯誤的時候,我們需要自定義缺谴。CustomDebugStringConvertible 是對錯誤的描述梭灿,我們需要拋出錯誤還是需要用Error拋出,Error的拋出錯誤描述如果需要用到上面的自定義錯誤描述篓足,我們就可以如上面一般使用鸟缕。conform localizedError protol 晶框,and then rewrite errorDescription.
- 怎么使用?
如上懂从,兩個代碼塊連起來就OK了