Merge pull request #5 from rock-n-code/feature/dependency-service

Feature: Dependency service
This commit is contained in:
Javier Cicchelli 2022-12-05 22:55:06 +01:00 committed by GitHub
commit 12b3f696c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 81 additions and 1 deletions

View File

@ -8,11 +8,16 @@ let package = Package(
products: [
.library(
name: "Libraries",
targets: ["APIService"]),
targets: [
"APIService",
"DependencyService"
]
),
],
dependencies: [],
targets: [
.target(name: "APIService"),
.target(name: "DependencyService"),
.testTarget(
name: "APIServiceTests",
dependencies: ["APIService"]

View File

@ -0,0 +1,29 @@
//
// Dependency.swift
// DependencyService
//
// Created by Javier Cicchelli on 05/12/2022.
// Copyright © 2022 Röck+Cöde. All rights reserved.
//
@propertyWrapper
public struct Dependency<D> {
// MARK: Properties
private let keyPath: WritableKeyPath<DependencyStore, D>
// MARK: Computed
public var wrappedValue: D {
get { DependencyStore[keyPath] }
set { DependencyStore[keyPath] = newValue }
}
// MARK: Initialisers
public init(_ keyPath: WritableKeyPath<DependencyStore, D>) {
self.keyPath = keyPath
}
}

View File

@ -0,0 +1,19 @@
//
// DependencyKey.swift
// DependencyService
//
// Created by Javier Cicchelli on 05/12/2022.
// Copyright © 2022 Röck+Cöde. All rights reserved.
//
public protocol DependencyKey {
// MARK: Associated types
associatedtype Value
// MARK: Properties
static var currentValue: Value { get set }
}

View File

@ -0,0 +1,27 @@
//
// DependencyStore.swift
// DependencyService
//
// Created by Javier Cicchelli on 05/12/2022.
// Copyright © 2022 Röck+Cöde. All rights reserved.
//
public struct DependencyStore {
// MARK: Properties
private static var current = Self()
// MARK: Functions
public static subscript<K>(key: K.Type) -> K.Value where K: DependencyKey {
get { key.currentValue }
set { key.currentValue = newValue }
}
public static subscript<D>(_ keyPath: WritableKeyPath<DependencyStore, D>) -> D {
get { current[keyPath: keyPath] }
set { current[keyPath: keyPath] = newValue }
}
}