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

Kotlin Multi Platform中如何导入Swift标准库的Hashable协议?

解决Kotlin/Native中实现Swift Hashable协议的问题

核心逻辑

Swift的Hashable协议在Objective-C层面通过NSObject的isEqual:和hash方法兼容,Kotlin/Native会自动将Kotlin类的equals()和hashCode()映射到这两个Obj-C方法,无需直接导入Swift的Hashable协议。


分场景处理

场景1:类继承自NSObject(如UIView、UIViewController等)

如果你的actual类已经继承NSObject子类(比如示例中的UIView),只需重写Kotlin的equals()和hashCode()方法,Swift会自动识别该类符合Hashable协议:

import platform.UIKit.UIView

actual final class Example actual constructor() : UIView() {
    private val someProperty: String = "test"

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Example) return false
        return someProperty == other.someProperty
    }

    override fun hashCode(): Int {
        return someProperty.hashCode()
    }
}

场景2:类未继承NSObject

如果类没有继承NSObject,需实现platform.objc.NSObjectProtocol(Obj-C基础协议,包含isEqual:和hash方法),同时重写equals()和hashCode():

import platform.objc.NSObjectProtocol
import platform.objc.objcProtocol

@objcProtocol
actual final class Example actual constructor() : NSObjectProtocol {
    private val someProperty: String = "test"

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Example) return false
        return someProperty == other.someProperty
    }

    override fun hashCode(): Int {
        return someProperty.hashCode()
    }
}

处理后,Swift代码中即可将Example类当作Hashable类型使用。


额外说明

无需尝试从platform或platform.objc下导入Swift的Hashable,Kotlin/Native通过Objective-C兼容层处理Swift标准库协议,直接用Kotlin自身的equals()和hashCode()实现即可完成映射。

内容的提问来源于stack exchange,提问作者Please Help Me

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:31:03