swift - 如何在 kotlin Multiplatform 和 Swift 中使用默认接口实现
问题描述
我正在使用 KMP 在 Android 和 iOS 上制作跨平台应用程序。我的问题是,当我在 Kotlin common main 中使用默认实现创建接口时,我无法在 iOS 中使用该实现,我需要在 Xcode 中重写代码。在我的方法中,没有特定于平台的内容。它们只是处理数字的函数(因此,只有一些 for 或 if 带有返回数字参数),所以对我来说只需编写一次方法就非常有用。有没有办法做到这一点?
这是 Kotlin 中的接口,带有方法和默认实现:
interface StandardValues {
fun nextValue(valueToCompare: String, currentStandardSpinner: String, currentUnitSpinner: Int): Pair<String, Int> {
var currentStandardArray = StandardValue.E12.valuesStandard
var indexSpinner = currentUnitSpinner
var valueConverted = 0.0f
try{
valueConverted = valueToCompare.toFloat()
} catch (e: NumberFormatException){
e.printStackTrace()
println(e)
}
if(valueToCompare.isNotEmpty()){
var previousValue: Float = 0.0f
if(valueConverted <= 1 && currentUnitSpinner == 0){
return Pair("0",0)
}
if(valueConverted < 1) {
for ((index, value) in currentStandardArray.withIndex()){
if ((valueConverted * 1000) > value){
previousValue = currentStandardArray[index]
}
}
if(indexSpinner != 0){
indexSpinner--
}
return Pair(previousValue.toString(), indexSpinner)
}
if(valueConverted <= currentStandardArray.first()){
if(indexSpinner == 0){
return Pair(currentStandardArray.first().toString(), 0)
}
previousValue = currentStandardArray.last()
indexSpinner--
return Pair(previousValue.toString(), indexSpinner)
}
for ((index, value) in currentStandardArray.withIndex()){
if (valueConverted > value){
previousValue = currentStandardArray[index]
}
}
return Pair(previousValue.toString(), indexSpinner)
}
return Pair(currentStandardArray.first().toString(), indexSpinner)
}
这是一个在 Android 中使用的示例:
class FindRealComponent: AppCompatActivity(), AdapterView.OnItemSelectedListener, StandardValues {
...
myTextView.text = nextValue("3", "pF", 0).first
}
在 Xcode 中:
class MeasureConverterViewController: UIViewController, StandardValues {
func nextValue(valueToCompare: String, currentStandardSpinner: String, currentUnitSpinner: Int) -> (String, Int) {
//I would like to avoid to write the same logic code
}
textView.text = nextValue(nextValue("3", "pF", 0).0
...
}
否则我认为我将在 Kotlin 中实现接口,并在 Swift 中创建一个带有扩展的协议。
谢谢。
解决方案
为了解决这个问题,我在 Android Studio 中实现了接口,并在同一个文件中创建了一个实现我的接口的类,因此在 Xcode 中我可以实例化该类的对象以使用默认方法。
安卓工作室:
interface StandardValues {
... //default methods
}
class StandardValuesImplementation: StandardValues{}
代码:
class MyViewController: UIViewController{
...
override func viewDidLoad() {
super.viewDidLoad()
...
let myClassImpl = StandardValuesImplementation()
let textView = MyClassImpl.myDefaultMethod
...
}
推荐阅读
- firefox-addon - Firefox 扩展调试器显示“此页面没有来源”
- c# - 如何通过分配具有相似字段的其他对象来创建对象
- python - 返回类实例时的 Numpydoc 样式约定
- android-fragments - 如何在 Java 项目中使用 NavigationExtensions.kt?
- c - 是否有受 setlocale() 影响的函数的完整列表?
- swift - 如何旋转具有固定锚点的 SCNNode?
- scala - 在 spark scala 中通过 cuid 聚合和求和向量稀疏
- python - 将 2 个列表与 ref 与元素的位置进行比较?
- ruby-on-rails - Rails 路由不会取消订阅控制器操作
- typescript - 在发送 axios 请求之前删除 cookie 中的 access_token