· 12 min read Posted by Daniel Bertoldi
Resolving Koin Dependencies from Swift
In a KMP project, your dependency graph usually looks like this:
// in :commonMain
interface UserRepository {
fun getName(): String
}
class UserRepositoryImpl : UserRepository {
override fun getName(): String = "John Doe"
}
class UserViewModel(private val repository: UserRepository)
val appModule = module {
single<UserRepository> { UserRepositoryImpl() }
factory { UserViewModel(get()) }
}
single and factory are called definitions in Koin.
There are a bunch others!
Now, if you come from Android, your first instinct is probably to reach into Koin straight from Swift. You can see that
Koin’s get wants a KClass, but Swift has no way to produce one. You think for a bit and come to the conclusion that
you just need a small helper in iosMain that can turn an Obj-C class back into its Kotlin counterpart. Something
like this:
// in :iosMain
fun Koin.get(objCClass: ObjCClass): Any {
val kClass = getOriginalKotlinClass(objCClass)!!
return get(kClass, null, null)
}
And call it like this in Swift:
let repository = koin.get(objCClass: UserRepositoryImpl.self) as! UserRepository
This looks good and the code compiles, awesome! But once you run it, it crashes with NoDefinitionFoundException. Ouch.
The reason for that is because single<UserRepository> { /* ... */} registers the definition under UserRepository,
not UserRepositoryImpl.
The implementation never entered the graph as a key of its own, which will also happen in Kotlin if you do the same thing there. The exception escapes into Swift without a @Throws, so you never get the chance to catch this error.
Try asking for the interface:
let repository = koin.get(objCClass: UserRepository.self)
And now Swift doesn’t even want to compile your code anymore. Frustrating. But that’s because Kotlin interfaces are
exported as protocols in Obj-C export.
UserRepository is a protocol
metatype, which
means it is not a class, so you can’t pass it as an ObjCClass at all.
So, how to circumvent this?
Well, you just have to stop asking Swift to name the type at all! Resolve the dependency in Kotlin (where get<T>()
knows exactly what T is) and hand Swift a typed function:
// :iosMain
@Suppress("unused")
object KoinDependencies : KoinComponent {
fun getUserRepository() = getKoin().get<UserRepository>()
}
Which works just fine! This is how you’d call it on the Swift side:
let userRepository = KoinDependencies.shared.getUserRepository()
But… What if you have a bunch of code you have to provide via Koin? Yes, you could just add more funs to your
KoinDependencies list, but at some point it starts to become a chore, especially since it’s one file you’d have to
change every time you create a new common interface.
So, while this approach works, it’s best suited for a handful of dependencies. This raises another question: is there any other way to achieve the same end result but without all the hassle?
Of course! Otherwise I bet you wouldn’t be reading this right now.
You can use the almighty power of generics to achieve the same result, but as you might expect, it’ll increase the complexity of your code a bit.
One Resolver to Rule Them All
If you’d rather not write a getter per dependency, you can take this approach, but you are forced to add two overloads. That’s because Kotlin classes and interfaces land on different sides of the Obj-C bridge, check it out:
@OptIn(BetaInteropApi::class)
object SharedDependencyResolver {
private object Resolver : KoinComponent
fun resolveOrNull(objCClass: ObjCClass): Any? {
val kClass = getOriginalKotlinClass(objCClass) ?: return null
return resolveOrNull(kClass)
}
fun resolveOrNull(objCProtocol: ObjCProtocol): Any? {
val kClass = getOriginalKotlinClass(objCProtocol) ?: return null
return resolveOrNull(kClass)
}
private fun resolveOrNull(kClass: KClass<*>): Any? =
runCatching { Resolver.getKoin().getOrNull<Any>(kClass, null, null) }.getOrNull()
}
Swift hands you an Obj-C type which can be either a class or a protocol, so there’s one public overload for each. But
as you can see, both do the same thing:
getOriginalKotlinClass
turns the Obj-C type back into the KClass it came from, and the private overload asks Koin for it. If for any reason
Swift passes something that isn’t a Kotlin type at all (like an UIView) you get null instead of a crash.
The return type is Any? because generic functions don’t survive the trip to Obj-C. Kotlin can’t promise Swift a
specific type, so the Swift helper casts the result back.
Finally, the private Resolver object exists solely to give us access to Koin without making SharedDependencyResolver
itself a KoinComponent that’s exposed to Swift.
We’ll talk more about resolveOrNull and what’s up with runCatching a little bit later, don’t worry.
And in your Swift code you’d add this helper:
func resolve<T>(_ type: T.Type) -> T? {
let raw: Any?
if let cls = type as? AnyClass {
raw = SharedDependencyResolver.shared.resolveOrNull(objCClass: cls)
} else if let proto = NSProtocolFromString(String(describing: type)) {
raw = SharedDependencyResolver.shared.resolveOrNull(objCProtocol: proto)
} else {
raw = nil
}
return raw as? T
}
Kotlin gives you two doors, and something has to pick the right one, that’s why we have this helper. Kotlin classes
come through as real Obj-C classes, so type as? AnyClass catches them and send them to the objCClass overload.
Interfaces are a bit trickier because they turn into protocols, and Swift won’t hand you a Protocol object from a
generic type, so the helper looks it up by name instead. We cover how and why in a little more detail in a bit.
Whatever comes back is Any?, and the final as? T turns it back into the type you asked for. That means no as! at
the call site, and no crash if something’s missing, you’ll just get nil.
Then resolve it like:
let viewModel = resolve(UserViewModel.self)
Passing parameters
Some definitions need a tiny bit of help to be built. Take a factory that expects a tag:
factory { (tag: String?) -> Logger(tag) }
Koin is perfectly happy to take parameters, so the resolver can just forward them. Add a parameters list to both
public overloads and hand it to Koin with parametersOf:
fun resolveOrNull(objCClass: ObjCClass, parameters: List<Any?>): Any? {
val kClass = getOriginalKotlinClass(objCClass) ?: return null
return resolveOrNull(kClass, parameters)
}
fun resolveOrNull(objCProtocol: ObjCProtocol, parameters: List<Any?>): Any? {
val kClass = getOriginalKotlinClass(objCProtocol) ?: return null
return resolveOrNull(kClass, parameters)
}
private fun resolveOrNull(kClass: KClass<*>, parameters: List<Any?> = emptyList()): Any? =
runCatching {
Resolver.getKoin().getOrNull<Any>(kClass, null) { parametersOf(*parameters.toTypedArray()) }
}.getOrNull()
Kotlin default arguments don’t reach Obj-C, so the default goes in the Swift helper instead. That way every existing call site stays exactly the same:
func resolve<T>(_ type: T.Type, parameters: [Any] = []) -> T? {
let raw: Any?
if let cls = type as? AnyClass {
raw = SharedDependencyResolver.shared.resolveOrNull(objCClass: cls, parameters: parameters)
} else if let proto = NSProtocolFromString(String(describing: type)) {
raw = SharedDependencyResolver.shared.resolveOrNull(objCProtocol: proto, parameters: parameters)
} else {
raw = nil
}
return raw as? T
}
let logger = resolve(Logger.self, parameters: ["MyTag"])
Swift and Kotlin don’t quite agree on what an Int is, though, so check the fine print before you go passing
numbers around.
The Fine Print
Now is the time to talk about the caveats, because you can bet your GTA VI copy that this resolver is not free. Some you pay once, others you keep paying for as long as it exists.
Gotchas when writing it
Give the two overloads different parameter names
Kotlin is pretty cool with two resolveOrNull functions, but just as long as their parameter types differ. Objective-C
however has no overloading, since Obj-C export builds each method’s selector from the function name plus its parameter
names.
If both parameters were called type, both functions would end up being mapped to the same selector and the sneaky
compiler would just quietly rename one of them. So in Swift you’d end up with resolveOrNull(type:) and
resolveOrNull(type_:), which may look odd for anyone who didn’t write this code. Naming the parameters objCClass
and objCProtocol gives you clean selectors, and the call site tells you which side of the bridge you’re on.
You’ll have to opt in to the interop APIs
This one may be not that big of a deal but nobody really likes to opt into stuff just for the sake of having something
more “easy” to handle. getOriginalKotlinClass, ObjCClass and ObjCProtocol are all marked @BetaInteropApi, so
you can’t escape opting into them. Since they are beta, there’s always the risk that they may change between Kotlin
releases, but that’s not necessarily a reason to avoid them. Just make sure to re-check if this code is still working
as expected each time you bump your Kotlin version, though.
What you’re trading away
Construction errors get swallowed
getOrNull may sound like it never throws, but it can only cover a missing definition. If for any reason a definition
exists but building it fails, Koin will throw an InstanceCreationException. And as you probably know, a Kotlin
exception that reaches Swift through a function without @Throws doesn’t become a Swift error, it straight up just
terminates the app.
If you use KaMPKit as an example for your KMP projects, you may notice it has a definition that would trip this up:
// Koin.kt in :commonMain
factory { (tag: String?) -> if (tag != null) baseLogger.withTag(tag) else baseLogger }
That definition expects a parameter, so if you try to resolve it with none the destructuring fails at construction
time. Hence why the resolver wraps the call in runCatching, because a definition that can’t be built becomes nil
instead of a crash.
runCatching can’t possibly know the difference between “this needed a parameter” and “this has a genuine bug in its
constructor” and so both become nil and your Swift code can’t tell them apart. If this bothers you like it bothers me,
you have two alternatives:
- Catch narrowly and log. Just catch
InstanceCreationExceptionand log it with Kermit and returnnull. Yes, this won’t stop Swift getting anilbut at least the reason will show up in the console log. - Let Swift take care of it. Drop
runCatchingand annotate the Kotlin functions with@Throws(InstanceCreationException::class). Swift will see athrowsfunction that you call withtry. This arguably can be more “honest”, but every single call site will pay for this.
Or, you know, just give the definition what it’s asking for and pass the parameters it needs.
Protocols are looked up by name
Classes are a bit simpler, your Swift helper only need to cast type as? AnyClass and it works like a charm. You can
thank Obj-C export which turns a Kotlin class into an Obj-C class at runtime. Yay!
But, like we mentioned earlier, protocols don’t get the same treatment. Inside a generic function, trying to cast
like type as? Protocol will always fail and the Swift compiler will make sure you know that by warning you. The only
way out in this case is to ask the Obj-C runtime for the Protocol by its name:
NSProtocolFromString(String(describing: type))
Calling String(describing:) on an imported protocol’s metatype returns its Obj-C runtime name, including the
framework prefix… It is also the most fragile line in the entire helper. If for any reason the string stops matching
the runtime name, NSProtocolFromString will return nil and so will resolve, with no errors thrown. That’s why
interfaces with a custom @ObjCName are worth testing explicitly.
Probably not. NSProtocolFromString is already a lookup in the Obj-C runtime’s protocol table, and building the
name with String(describing:) costs well under a microsecond. That’s nothing next to Koin actually building your
dependency. If you ever do call resolve in a hot path, cache the Protocol per type, never the resolved
instance, or you’ll quietly turn every factory into a singleton.
Parameters cross the bridge untyped
Parameters go through as a plain [Any], so nothing checks that what Swift sends matches what the definition
expects. Kotlin and Swift have to agree on their own, and sometimes that doesn’t happen.
A Swift Int is 64 bits, so it lands in Kotlin as a Long. A definition expecting (count: Int) fails to build, and
runCatching turns that into a nil. Pass Int32(3) or KotlinInt(int: 3) instead. The same is true for nil: a
Swift [Any] can’t hold it, so pass NSNull() and Kotlin will see a null.
Get the order or the count wrong and, you guessed it, nil again.
Typos move from compile time to runtime
With KoinDependencies, asking for something that doesn’t exist is a compile error. With the resolver,
resolve(UserRepositoryImpl.self) compiles fine, but returns nil. This is the exact same NoDefinitionFoundException
from the start of this post but wearing a different makeup.
Qualifiers don’t make it across either, so anything that needs one still gets its own function in
KoinDependencies. How to mitigate this? By creating a unit test.
KaMPKit already calls checkModules
in iosTest that verifies that every definition can be built. If you make the KClass overload internal, a
small test can cover keys Swift asks for that does not actually exists:
class SwiftResolvableTypesTest {
// Every type Swift resolves through SharedDepdendencyResolver
private val swiftTypes = listOf(
UserRepository::class,
UserViewModel::class,
)
@BeforeTest
fun setUp() { startKoin { modules(appModule) } }
@AfterTest
fun tearDown() = stopKoin()
@Test
fun everySwiftTypeResolves() {
swiftTypes.forEach { kClass ->
assertNotNull(
SharedDependencyResolver.resolveOrNull(kClass),
"${kClass.simpleName} is not resolvable from Swift",
)
}
}
}
This will probably make you go like “Wait, you’ve just moved your list of dependencies from KoinDependencies into a
test!”, and to that all I can say is: Yes.
But a list in a test doesn’t ship, doesn’t need a getter per entry and it fails loudly in CI instead of quietly in production, so it’s up to you if you feel that’s enough reason to create this test class.
Which one to choose?
One more thing worth pondering before you reach for either: how much is Swift actually pulling out of Koin?
If you share your ViewModels, Swift often only needs a handful of entry points, and the simple approach covers that easily. Case in point, KaMPKit gets away with a single getter.
If that’s your situation, or you’re still on the fence about which one is best, we will always recommend the simpler approach first. It’s easier, the compiler has your back and it’s less error prone.
The resolver starts to earn its keep when sharing more isn’t an option, like when you’re adopting KMP gradually
in an existing iOS app or your team prefers to keep presentation native, and you can see a ton of dependencies
heading for iOS. Just remember that the resolver by itself doesn’t replace KoinDependencies entirely,
since anything that needs a qualifier will still need its own function.
If you go with the resolver, chances are you’ll end up with both. resolve() for the plain stuff and a few
explicit getters for the rest. Oh, and don’t forget the test that will keep the resolver honest!