DEV Community

tyoc213
tyoc213

Posted on

1 1

Swinject, protocolos y tipos de datos

En general al empezar un proyecto si tienes la costumbre de crear un singleton para pasar de manera sencilla valores de un lado a otro, en su lugar deberías considerar la inyección de dependencias.

Una forma rápida de lograrlo es usar una librería que implemente ese patron, en nuestro caso usaremos Swinject y para hacer las cosas más fáciles de inyectar y pedir al contenedor, haremos uso de el protocolos y una extensión al mismo para que se pueda inyectar desde un String hasta una clase, estructura, valor de enumeración, etc.

// tyoc213

import Swinject

enum InjectName:String {
    case myValue
    case serviceResponse
    case anInt
}

extension Container {
    func resolve<R>(from: InjectName) -> R {
        let r:Inject<R> = resolve(InjectContainer.self, name: from.rawValue) as! Inject<R>
        return r.value
    }

    func register<T>(from: InjectName, value:T){
        register(InjectContainer.self, name: from.rawValue) {_ in Inject<T>(value: value)}
    }
}

protocol InjectContainer {
}

struct Inject<T>:InjectContainer{
    var value: T
    init(value:T) {
        self.value = value
    }
}

Entonces, una vez creado el contenedor en el appDelegate se puede insertar y extraer datos de la siguiente forma

contenedor.register(.anInt, 1)
contenedor.register(serviceResponse, someInstance)
contenedor.register(.myValue, "some value")

Y para obtener esos datos

let a:Int = contenedor.resolve(.anInt)
let a:ResponseService = contenedor.resolve(.serviceResponse)
let a:String = contenedor.resolve(.myValue)

Se tiene que especificar el tipo de dato en la asignación ya que al ser un template necesita resolver el tipo de dato al momento de compilar.

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay