[Shared] Adds @UserInfoValue property wrapper for ALTLocalizedErrors

ALTLocalizedErrors now automatically include all properties annotated with @UserInfoValue in userInfo when bridged to NSError.
This commit is contained in:
Riley Testut
2023-05-11 14:29:45 -05:00
parent 63868a2ff0
commit 3d712af6c5
3 changed files with 62 additions and 1 deletions

View File

@@ -73,13 +73,15 @@ public extension ALTLocalizedError
}
var errorUserInfo: [String : Any] {
let userInfo: [String: Any?] = [
var userInfo: [String: Any?] = [
NSLocalizedFailureErrorKey: self.errorFailure,
ALTLocalizedTitleErrorKey: self.errorTitle,
ALTSourceFileErrorKey: self.sourceFile,
ALTSourceLineErrorKey: self.sourceLine,
]
userInfo.merge(self.userInfoValues) { (_, new) in new }
return userInfo.compactMapValues { $0 }
}
@@ -132,6 +134,21 @@ public extension ALTLocalizedError
}
}
private extension ALTLocalizedError
{
var userInfoValues: [(String, Any)] {
let userInfoValues = Mirror(reflecting: self).children.compactMap { (label, value) -> (String, Any)? in
guard let userInfoValue = value as? any UserInfoValueProtocol,
let key: any StringProtocol = userInfoValue.key ?? label?.dropFirst() // Remove leading underscore
else { return nil }
return (String(key), userInfoValue.wrappedValue)
}
return userInfoValues
}
}
public struct DefaultLocalizedError<Code: ALTErrorEnum>: ALTLocalizedError
{
public let code: Code