Created
September 19, 2020 20:14
-
-
Save rayfix/e63b84c12f47650fad8d7d50697eb9f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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