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了