Skip to content

Instantly share code, notes, and snippets.

@akbsteam
Created March 25, 2018 14:46
Show Gist options
  • Select an option

  • Save akbsteam/6f6c860809a9dc77443d7b3842eff6e4 to your computer and use it in GitHub Desktop.

Select an option

Save akbsteam/6f6c860809a9dc77443d7b3842eff6e4 to your computer and use it in GitHub Desktop.
import Foundation
precedencegroup ForwardApplication
{
associativity: left
higherThan: AssignmentPrecedence
}
precedencegroup ForwardComposition
{
associativity: left
higherThan: ForwardApplication
}
infix operator |>: ForwardApplication // apply rhs to lhs, returning rhs type
infix operator >>>: ForwardComposition // compose lhs and rhs into one
public func |> <A, B>(a: A, f: (A) -> B) -> B
{
return f(a)
}
public func >>> <A, B, C>(f: @escaping (A) -> B, g: @escaping (B) -> C) -> ((A) -> C)
{
return { a in
a |> f |> g
}
}
struct Item: Codable
{
var title: String
var subtitle: String
}
struct Filepath
{
private(set) var value: String
init?(in bundle: Bundle = .main,
ofType fileExt: String = "json",
named name: String?)
{
guard let path = bundle.path(forResource: name, ofType: fileExt)
else { return nil }
self.value = path
}
}
struct Unwrap
{
typealias StringToData = (String) -> Data?
typealias PathToString = (Filepath) -> String?
static func fMap<T, U>(_ fnc: @escaping (T) -> U?) -> (T?) -> U?
{
return { $0.flatMap(fnc) }
}
static let stringToData: StringToData = { $0.data(using: .utf8) }
static let pathToString: PathToString = {
try? String(contentsOfFile: $0.value, encoding: .utf8)
}
static func decodeJSON<T: Codable>() -> (Data) -> T?
{
return { try? JSONDecoder().decode(T.self, from: $0) }
}
}
extension Unwrap
{
static func jsonData<T: Codable>(in bundle: Bundle = .main,
named name: String) -> T?
{
return Filepath(in: bundle, ofType: "json", named: name)
|> fMap(pathToString)
>>> fMap(stringToData)
>>> fMap(decodeJSON())
}
}
let items: [Item]? = Unwrap.jsonData(named: "test")
items?.forEach { print($0) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment