Skip to content

Instantly share code, notes, and snippets.

View fmo91's full-sized avatar

Fernando Martín Ortiz fmo91

View GitHub Profile
enum Dependencies {
// ...
final class Container {
// ...
func register(_ dependency: Any, for key: Dependencies.Name = .default) {
dependencies.append((key: key, value: dependency))
}
func resolve<T>(_ key: Dependencies.Name = .default) -> T {
return (dependencies
// We will create an enum as a namespace
enum Dependencies {
// The same pattern that NotificationCenter's Name struct
// follows.
struct Name: Equatable {
let rawValue: String
static let `default` = Name(rawValue: "__default__")
static func == (lhs: Name, rhs: Name) -> Bool { lhs.rawValue == rhs.rawValue }
}
struct Person {
let name: String
}
struct People {
// This empty array will be the wrappedValue in the init.
@Sorted(by: { $0.name < $1.name }) var items: [Person] = []
}
var people = People()
// @propertyWrapper annotation makes this
// struct a property wrapper.
// It will be a generic struct because we will make
// it work with any kind of value type.
@propertyWrapper
struct Sorted<T> {
// Internally, we will store the actual value of
// the array in this property
private var value: [T]
class ProductsCalculator {
// ...
func calculateTotal(using taxesCalculator: TaxesCalculatorType) -> Double {
let subtotal = products.map({ $0.price }).reduce(0, +)
return taxesCalculator.applyTaxes(to: subtotal)
}
}
class ProductsCalculator {
private let taxesCalculator: TaxesCalculatorType
// ...
init(taxesCalculator: TaxesCalculatorType) {
self.taxesCalculator = taxesCalculator
}
func calculateTotal() -> Double {
protocol TaxesCalculatorType {
func applyTaxes(to subtotal: Double) -> Double
}
class TaxesCalculatorA: TaxesCalculatorType {
func applyTaxes(to subtotal: Double) -> Double {
// Some weird taxes logic 😨
subtotal * 1.21
}
}
class TaxesCalculator {
func applyTaxes(to subtotal: Double) -> Double {
// Some weird taxes logic 😨
subtotal * 1.21
}
}
class ProductsCalculator {
private let taxesCalculator = TaxesCalculator()
struct Product {
// ...
let price: Double
}
class ProductsCalculator {
private var products: [Product] = []
func add(product: Product) {
products.append(product)
final class ViewController: UIViewController {
// MARK: - Views -
@IBOutlet private weak var firstNumberTextField: UITextField!
@IBOutlet private weak var secondNumberTextField: UITextField!
@IBOutlet private weak var operationTextField: UITextField!
@IBOutlet private weak var resultLabel: UILabel!
private var operationPickerView: UIPickerView!