Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created Sep 19, 2020
Embed
What would you like to do?
import Combine
struct Location {
}
//protocol WeatherService {
// func getTemperature(location: Location) -> AnyPublisher<Double, Error>
//}
//
//final class MockWeather: WeatherService {
//
// var temperature: Result<Double, Error> = .success(20)
//
// func getTemperature(location: Location) -> AnyPublisher<Double, Error> {
// switch temperature {
// case .success(let temp):
// return Just(temp)
// .setFailureType(to: Error.self)
// .eraseToAnyPublisher()
// case .failure(let error):
// return Fail(error: error).eraseToAnyPublisher()
// }
// }
//}
struct WeatherService {
var getTemperature: (Location) -> AnyPublisher<Double, Error>
}
extension WeatherService {
static func happy(temp: Double) -> Self {
WeatherService(getTemperature: { location in
Just(temp).setFailureType(to: Error.self).eraseToAnyPublisher()
})
}
}
extension WeatherService {
static let real = WeatherService(getTemperature: { location in
Just(20.0).setFailureType(to: Error.self).eraseToAnyPublisher()
})
}
final class WeatherViewModel: ObservableObject {
@Published var temperature: Double?
let service: WeatherService
init(service: WeatherService) {
self.service = service
}
}
WeatherViewModel(service: .happy(temp: 20))
WeatherViewModel(service: .real)
protocol Printable {
func describe() -> String
}
struct Printing<A> {
var describe: (A) -> String
}
struct User {
var login: String
var email: String
static let short = Printing<User> { user in
user.login
}
static let long = Printing<User> { user in
user.login + " " + user.email
}
}
let ray = User(login: "ray", email: "ray@example.com")
func describe<A>(thing: A, printer: Printing<A>) {
print(printer.describe(thing))
}
describe(thing: ray, printer: User.short)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment