Swiftpack.co -  dariopellegrini/Cobb as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
dariopellegrini/Cobb
Swift dependency injection
.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: "username@domanin.com", 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, pellegrini.dario.1303@gmail.com

License

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

GitHub

link
Stars: 0
Last commit: 1 week ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Related Packages

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