BodyDecoder
public struct BodyDecoder<Body>
A generic value type to decode response body content from Data
Usage
You specilize the Decoder with the type you want to decode, and pass in a closure to convert Data into the type:
let decoder = BodyDecoder<MyType> { data in
// return `MyType?` or throw an error
}
Reusability
Typically, you will want to re-use body decoders for a given type.
The best way to do this is to declare a your decoder in a type-constrained extensions
extension BodyDecoder where Body == MyType {
static var myDecoder: Self {
.init { data in
// Convert `Data?` into `MyType?` or throw an error
}
}
}
// You can now use this decoder with a `ComposableRequest`, or when creating type that conform to `Requestable`
let request = ComposableRequest<Any, MyType, Error>
.decode(with: .myDecoder)
struct MyRequest: Requestable {
var responseDecoder: BodyDecoder<MyType> {
.myDecoder
}
}
Alternatively, if you want to create an decoder for a type you have control over, simply have that type conform toAutomaticBodyDecoding.
A default decoder is created for you automatically, and added by default to every Requestable or ComposableRequest type that has been specialized with your type as its ResponseBody
extension MyType: AutomaticBodyDecoding {
init?(fromData: Data?) throws {
// Initialize `MyType`, return `nil`, or throw an error
}
}
// `default` is created for you automatically, and need not be added to `Requestable` or `ComposableRequest` instances.
let decoder = BodyDecoder<MyType>.default
Ombi provides default body decoders for the following types:
StringDataAnyJSON- Types that conform to
Decodable - Types that conform to
AutomaticBodyDecoding
See similar types BodyEncoder and ResponseValidator
-
Create a
BodyDecoderDeclaration
Swift
public init(_ handler: @escaping Handler)Parameters
handlerThe decoding closure
-
Closure used to decode
BodyfromDataDeclaration
Swift
public typealias Handler = (Data?) throws -> Body? -
The handler that decodes
DataDeclaration
Swift
public let decode: Handler -
A fatal decoder that will cause a runtime failure
Declaration
Swift
static var fatal: `Self` { get }
-
Create a
Stringbody decoder with specified encodingDeclaration
Swift
init(encoding: String.Encoding = .utf8)Parameters
encodingThe encoding of the
String -
The default
Stringbody decoderDeclaration
Swift
static var `default`: `Self` { get }
-
The default
Databody decoderDeclaration
Swift
static var `default`: `Self` { get }
-
Create a decoder for a
Codableusing aJSONDecoderDeclaration
Swift
static func json(decoder: JSONDecoder = JSONDecoder()) -> BodyDecoder<Body>Parameters
decoderThe
JSONDecoderto use for decodingReturn Value
The decoder
-
The default
CodabledecoderDeclaration
Swift
static var `default`: `Self` { get }
-
The default decoder for types that conform to
AutomaticBodyDecodingDeclaration
Swift
static var `default`: `Self` { get }
View on GitHub
Install in Dash
BodyDecoder Structure Reference