在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:Anviking/Decodable开源软件地址:https://github.com/Anviking/Decodable开源编程语言:Swift 99.3%开源软件介绍:DecodableSimple and strict, yet powerful object mapping made possible by Swift 2's error handling. Greatly inspired by Argo, but without a bizillion functional operators. struct Repository {
let name: String
let description: String
let stargazersCount: Int
let language: String?
let sometimesMissingKey: String?
let owner: User // Struct conforming to Decodable
let defaultBranch: Branch // Struct NOT conforming to Decodable
var fullName: String { return "\(owner.login)/\(name)" }
}
extension Repository: Decodable {
static func decode(j: Any) throws -> Repository {
return try Repository(
name: j => "nested" => "name",
description: j => "description",
stargazersCount: j => "stargazers_count",
language: j => "language",
sometimesMissingKey: j =>? "sometimesMissingKey",
owner: j => "owner",
defaultBranch: Branch(name: j => "default_branch")
)
}
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
let repo = try [Repository].decode(json)
} catch {
print(error)
} How does it work?A protocolpublic protocol Decodable {
static func decode(json: Any) throws -> Self
} A parse-functionpublic func parse<T>(json: Any, path: [String], decode: (Any throws -> T)) throws -> T And shameless operator-overloadingThe too-many generated overloads, all calling the An overload may look like this: public func => <T: Decodable>(json: Any, keyPath: KeyPath) throws -> T KeyPathsKeypaths can be created from string and array literals as well as with explicit initializers. They can also be joined using the operators
let a: KeyPath = "a"
let b: KeyPath = ["a", "b"]
let c: KeyPath = "a" => "b" => "c"
let string: String? = json =>? "key1" => "key2" => "key3"`
^^^^ allowed to be missing ErrorsErrors will be caught and rethrown in the decoding process to backpropagate metadata, like the JSON object that failed decoding, the key path to it, and the root JSON object. From DecodingError.swift: public enum DecodingError: ErrorProtocol, Equatable {
/// Thrown when optional casting from `Any` fails.
///
/// This can happen both when trying to access a key on a object
/// that isn't a `NSDictionary`, and failing to cast a `Castable`
/// primitive.
case typeMismatch(expected: Any.Type, actual: Any.Type, Metadata)
/// Thrown when a given, required, key was not found in a dictionary.
case missingKey(String, Metadata)
/// Thrown from the `RawRepresentable` extension when
/// `init(rawValue:)` returned `nil`.
case rawRepresentableInitializationError(rawValue: Any, Metadata)
/// When an error is thrown that isn't `DecodingError`, it
/// will be wrapped in `DecodingError.other` in order to also provide
/// metadata about where the error was thrown.
case other(ErrorProtocol, Metadata)
} let dict: NSDictionary = ["object": ["repo": ["owner": ["id" : 1, "login": "anviking"]]]]
do {
let username: String = try dict => "object" => "repo" => "owner" => "name"
} catch let error {
print(error)
}
//
// MissingKeyError at object.repo.owner: name in {
// id = 1;
// login = anviking;
// } Handling ErrorsExpressions like For convenience there is an operator,
Customization
public protocol DynamicDecodable {
associatedtype DecodedType
static var decoder: (Any) throws -> DecodedType {get set}
} This allows Decodable to implement default decoding closures while allowing you to override them as needed. // Lets extend Bool.decoder so that it accepts certain strings:
Bool.decoder = { json in
switch json {
case let str as String where str == "true":
return true
case let str as String where str == "false":
return false
default:
return try cast(json)
}
} Note that when extending new types to conform to The default Date.decoder = Date.decoder(using: formatter)
When |
Swift version | Compatible tag or branch |
---|---|
Swift 4.0 | 0.6.0 |
Swift 3.0 | v0.5 |
Swift 2.3 | v0.4.4 |
Swift 2.2 | v0.4.3 |
Due to collisions with the standard library you will have to import ambiguous symbols specifically, in addition to Decodable
as a whole.
This means you likely want the following
import Decodable
import protocol Decodable.Decodable
and you can import other symbols, e.g KeyPath
, DecodingError
, in a simlilar fashion (using import struct
and import enum
)
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论