Created
January 24, 2023 09:08
-
-
Save jegnux/103b68804d0044beecd56f08a68204e3 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 Foundation | |
import SwiftUI | |
public struct DependencyBag<Dependency, Content: View> : View { | |
public init( | |
dependencyFactory: @escaping () -> Dependency, | |
@ViewBuilder view contentFactory: @escaping (Dependency) -> Content | |
) { | |
self.dependencyFactory = dependencyFactory | |
self.contentFactory = contentFactory | |
} | |
@State fileprivate var bag = Bag<Dependency>() | |
private let dependencyFactory: () -> Dependency | |
private let contentFactory: (Dependency) -> Content | |
public var body: some View { | |
contentFactory(bag.getOrMake(using: dependencyFactory)) | |
} | |
} | |
private final class Bag<Dependency> { | |
private var dependency: Dependency? | |
func getOrMake(using factory: () -> Dependency) -> Dependency { | |
if let dependency { | |
return dependency | |
} else { | |
dependency = factory() | |
return dependency! | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: