Skip to content

Instantly share code, notes, and snippets.

View eMdOS's full-sized avatar

Emilio Ojeda eMdOS

  • Zapopan, Jalisco
View GitHub Profile
@eMdOS
eMdOS / Combine Publishers Example.swift
Created May 1, 2020 23:36
Medium: Extending the Swift's Result type
URLSession.shared
.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: MoviesPage.self, decoder: JSONDecoder())
// Obj-C
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)
urlcompletionHandler:(void (^)(
NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error)
)completionHandler;
// Swift
func dataTask(
public extension URLSession {
typealias DataTaskResult = Result<(data: Data, response: URLResponse), Error>
typealias DataTaskResultCompletion = (DataTaskResult) -> Void
func dataTask(
with url: URL,
completion: @escaping DataTaskResultCompletion
) -> URLSessionDataTask {
dataTask(with: url) { (data, response, error) in
if let error = error {
public extension Result where Success == (data: Data, response: URLResponse) {
func map<T>(_ keyPath: KeyPath<Success, T>) -> Result<T, Failure> {
switch self {
case .success(let response):
return .success(response[keyPath: keyPath])
case .failure(let error):
return .failure(error)
}
}
}
public protocol DecodableDataDecoder {
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T: Decodable
}
extension JSONDecoder: DecodableDataDecoder {}
extension PropertyListDecoder: DecodableDataDecoder {}
public extension Result where Success == Data {
func decode<T: Decodable>(_ type: T.Type, using decoder: DecodableDataDecoder) -> Result<T, Error> {
do {
func geNowPlaying(completion: @escaping (Result<MoviesPage, Error>) -> Void) {
URLSession.shared
.dataTask(with: url) { result in
completion(
result
.map(\.data)
.decode(MoviesPage.self, using: JSONDecoder())
)
}.resume()
}
func string(from int: Int) -> String {
String(int)
}
func compose<A, B, C>(
f: @escaping (A) -> B, // f: A -> B
g: @escaping (B) -> C // g: B -> C
) -> (A) -> C { // h: A -> C = g • f
return { a in
g(f(a)) // g • f
}
}
// ... then
infix operator <> : AdditionPrecedence
public protocol Semigroup {
static func <> (left: Self, right: Self) -> Self
}
extension String: Semigroup {
public static func <> (left: String, right: String) -> String {
left + right
}
}