Swiftpack.co - dariopellegrini/Cobb as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by dariopellegrini.
dariopellegrini/Cobb 0.2.2
Swift dependency injection
⭐️ 0
🕓 2 years ago
iOS macOS tvOS
.package(url: "https://github.com/dariopellegrini/Cobb.git", from: "0.2.2")

Swift dependency injection

Cobb

A light Swift library to manage dependency injection easily.

Installation

CocoaPod

Install with CocoaPod.

pod 'Cobb'

Swift Package Manager

Install Cobb simply adding GitHub link to Xcode project through Swift Package Manager.

https://github.com/dariopellegrini/Cobb

Usage

Let's take as example a simple achitecture.


struct NetworkService {
  func login(username: String, password: String) -> User {
    ...
  }
}

struct DatabaseService {
  func insert(user: User) {
    ...
  }
}

struct Repository {
  let network: NetworkService
  let database: DatabaseService
  
  func login(username: String, password: String) -> User {
    let user = network.login(username: username, password: password)
    database.insert(user: user)
    return user
  }
}

Using Cobb builders it's possible to define dependencies of application's layers.

Dependencies {
  Factory { Database() }
  Factory { NetworkService() }
  Singleton { Repository(network: inject(), database: inject()) }
}.dream()

Then in other classes (such as UIViewController) or structs.

class FirstViewController: UIViewController {
  @Injected var repository: Repository
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    DispatchQueue.global(qos: .utility).async {
      let user = repository.login(username: "[email protected]", password: "password")
      
      DispatchQueue.main.async {
        // Update UI
      }
    }
  }
}

injected() resolves automatically dependencies defined in Dependencies builder.
Factory defines a dependency that when resolved returns a new instance.
Singleton defines a dependency that behaves like a singleton, so when resolved returns the same instance through the whole application.
dream() actually configures dependencies.
@Injected resolves the dependency and return an instance of the specified type.

That's it!

Author

Dario Pellegrini, [email protected]

License

Cobb is available under the MIT license. See the LICENSE file for more info.

GitHub

link
Stars: 0
Last commit: 2 years ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Related Packages

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics