Kotlin/Nativeの String.replace のバグを回避する
kyamada,•KotlinNative
Kotlin/Native の String.replace のバグ
Kotlin/Native(1.8.0) の String.replace メソッドには以下の不具合があります。いずれも、iOS で実行した時に発生するバグです。
- 
特定の文字を置換したときの結果が Android と iOS で異なる 
- 
正規表現で置換するとクラッシュする 
この問題を避けるためには、Kotlin/Native の String.replace を使わず、Android/iOS それぞれで文字列置換処理を実装する必要があります。
Android/iOS それぞれで文字列置換処理を実装する
Kotlin/Native の shared モジュールで Interface を作成します
TextReplacer.kt
package com.kyamada.listentonovels.shared.model.text
 
interface TextReplacer {
    fun replace(text: String, oldValue: String, newValue: String, useRegex: Boolean): String
}Android プロジェクト内で TextReplacerImpl を実装します。
TextReplacerImpl.kt
package com.kyamada.listentonovels.androidApp.model.text
 
import com.kyamada.listentonovels.shared.model.text.TextReplacer
 
class TextReplacerImpl : TextReplacer {
    override fun replace(
        text: String,
        oldValue: String,
        newValue: String,
        useRegex: Boolean
    ): String {
        return if (useRegex) {
            text.replace(oldValue.toRegex(), newValue)
        } else {
            text.replace(oldValue, newValue)
        }
    }
}iOS プロジェクト内で TextReplacerImpl を実装します。
TextReplacerImpl.swift
import Foundation
import shared
 
class TextReplacerImpl: NSObject {
}
 
extension TextReplacerImpl: TextReplacer {
    func replace(text: String, oldValue: String, newValue: String, useRegex: Bool) -> String {
        if useRegex {
            return text.replacingOccurrences(of: oldValue, with: newValue, options: .regularExpression)
        } else {
            return text.replacingOccurrences(of: oldValue, with: newValue)
        }
    }
}
 あとは、TextReplacerImpl のインスタンスをアプリ起動時などのタイミングで shared モジュールに渡し、そのインスタンスを使って置換処理を行います。
© 品川アプリ.RSS