You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KMP中Swift调用EventBus带reified内联post函数报错求助

解决KMP中Swift调用EventBus.post报错问题

问题场景

在KMP项目中实现了如下EventBus:

typealias Observer = (Any) -> Unit

object EventBus {
    //// 其他代码

    @Throws(Throwable::class)
    fun <T : Any> post(
        clazz: KClass<T>,
        event: T,
    ) {
        observers.value[clazz]?.forEach { it.invoke(event) }
    }

    @Throws(Throwable::class)
    inline fun <reified T : Any> post(event: T) {
        post(T::class, event)
    }
}

尝试在Swift中调用post函数时:

let event = LoadSuccessModel(message: "String")
do {
    try EventBus.shared.post(event: event)
}
catch {
    print("\(error)")
}

出现以下错误:

Error Domain=KotlinException Code=0 "unsupported call of reified inlined function `eventbus.EventBus.post`" UserInfo={NSLocalizedDescription=unsupported call of reified inlined function `eventbus.EventBus.post`, KotlinException=kotlin.IllegalStateException: unsupported call of reified inlined function `eventbus.EventBus.post`, KotlinExceptionOrigin=}

错误原因

Swift与Kotlin的互操作不支持调用带reified泛型的inline函数,这类函数的泛型类型信息依赖Kotlin编译期的内联处理,无法被Swift正确解析调用。

解决方案

给EventBus添加一个无需泛型参数的普通函数,专门供Swift调用:

修改Kotlin代码

typealias Observer = (Any) -> Unit

object EventBus {
    //// 其他代码

    @Throws(Throwable::class)
    fun <T : Any> post(
        clazz: KClass<T>,
        event: T,
    ) {
        observers.value[clazz]?.forEach { it.invoke(event) }
    }

    @Throws(Throwable::class)
    inline fun <reified T : Any> post(event: T) {
        post(T::class, event)
    }

    // 添加供Swift调用的重载函数
    @Throws(Throwable::class)
    fun postEvent(event: Any) {
        post(event::class, event)
    }
}

修改Swift调用代码

let event = LoadSuccessModel(message: "String")
do {
    try EventBus.shared.postEvent(event: event)
}
catch {
    print("\(error)")
}

另一种可选方案

如果希望保留泛型调用的形式,也可以让Swift直接调用带KClass参数的post函数,但需要手动获取对应的Kotlin类引用:

let event = LoadSuccessModel(message: "String")
do {
    try EventBus.shared.post(clazz: LoadSuccessModel.self.kotlinClass, event: event)
}
catch {
    print("\(error)")
}

不过这种方式需要确保LoadSuccessModel在KMP中正确导出了kotlinClass属性,相比第一种方案稍显繁琐。

内容的提问来源于stack exchange,提问作者herz88888888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:40:09