Cobb 0.2.2

Cobb 0.2.2

Maintained by Dario Pellegrini.



Cobb 0.2.2

  • By
  • author

Cobb

A light Swift library to manage dependency injection easily.

Installation

Install with CocoaPod.

pod '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 behavies like a singleton, so when resolved returns the same instance through the whole application.
dream() actually configure 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.