Skip to content

Instantly share code, notes, and snippets.

@serhiybutz
serhiybutz / conf_deps_by_value1.swift
Created February 2, 2024 17:02
Injecting dependencies by value, scenario 1
import Foundation
// MARK: - (1) Original app blob scenario:
/// We have the app blob with original code. It contains a builder to build a UI component, which contains a UIView:
/// _Note: We use enums just for namespaces._
enum AppBlob {
/// Some class that needs to be run on Main thread:
struct UIView {
init() {
@serhiybutz
serhiybutz / conf_deps_by_value2.swift
Created February 2, 2024 16:58
Injecting dependencies by value, scenario 2
import Foundation
// MARK: - (1) Original app blob scenario:
/// We have the app blob with original code:
/// _Note: We use enums just for namespaces._
enum AppBlob {
/// Some sigleton (global state):
static var someSingleton: String?
/// Some view:
/// Traffic consumer account.
struct TrafficAccount {
// MARK: - Properties (State)
private let balance = Property<Double>(value: 0) // remaining money
private let traffic = Property<Double>(value: 0) // traffic consumed
private let sharedManager = SharedManager()
// MARK: - Queries
public var currentBalance: Double {
/// Traffic consumer account.
final class TrafficAccount {
// MARK: - Properties (State)
private var balance: Double = 0 // remaining money
private var traffic: Double = 0 // traffic consumed
// MARK: - Queries
public var currentBalance: Double { balance }
public var currentTraffic: Double { traffic }
public var summary: (balance: Double, traffic: Double) { (balance: balance, traffic: traffic) }
public final class SharedManager {
private var registry = Registry()
private let mutex = NSLock()
internal func internalBorrow(_ props: [AnyObject], accessBlock: () -> Void) {
let active = activateBorrowingFor(props)
defer {
deactivateBorrowing(active)
active.revoke()
}
accessBlock()
final class Borrowing {
private let props: [AnyObject]
private let revokeCond = NSCondition()
private var isRevoked = false
init(_ props: [AnyObject]) {
self.props = props
}
func wait() {
revokeCond.lock()
defer { revokeCond.unlock() }
extension SharedManager {
public func borrow<A>(_ a: Property<A>,
accessBlock: (inout Accessor<A>) -> Void)
{
var _a = Accessor(a)
internalBorrow([a]) {
accessBlock(&_a)
}
}
public func borrow<A, B>(_ a: Property<A>,
public struct Accessor<T> {
private let prop: Property<T>
internal init(_ p: Property<T>) {
self.prop = p
}
public var value: T {
get { prop.value }
set { prop.value = newValue }
}
}
public final class Property<T> {
internal var value: T
public init(value: T) {
self.value = value
}
}
class Foo {
let sharedCounter = Shared(value: 0)
let sharedName = Shared(value: "")
let sm = SharedManager()
func reset() {
sm.borrow(sharedCounter, sharedName) { sharedCounter, sharedName in
sharedCounter.value = 0
sharedName.value = ""