Swift 5 : String. UTF16View.Index(encodedOffset: l) 弃用

标签 swift swift5

我正在使用此代码将连字符插入字符串以实现更好的自动换行。使用 Swift 5 我得到的信息是

String.UTF16View.Index(encodedOffset: l)

将被弃用。但我无法找出正确的参数。有什么想法吗?

import Foundation

extension String {

    func hyphenated(languageCode: String) -> String {
        let locale = Locale(identifier: languageCode)
        return self.hyphenated(locale: locale)
    }

    func hyphenated(locale: Locale) -> String {
        guard CFStringIsHyphenationAvailableForLocale(locale as CFLocale) else { return self }

        var s = self

        let fullRange = CFRangeMake(0, s.utf16.count)
        var hyphenationLocations = [CFIndex]()
        for (i, _) in s.utf16.enumerated() {
            let location: CFIndex = CFStringGetHyphenationLocationBeforeIndex(s as CFString, i, fullRange, 0, locale as CFLocale, nil)
            if hyphenationLocations.last != location {
                hyphenationLocations.append(location)
            }
        }

        for l in hyphenationLocations.reversed() {
            guard l > 0 else { continue }
            let strIndex = String.UTF16View.Index(encodedOffset: l)
            // insert soft hyphen:
            s.insert("\u{00AD}", at: strIndex)
            // or insert a regular hyphen to debug:
            // s.insert("-", at: strIndex)
        }

        return s
    }
}

最佳答案

l 是字符串 s 中 UTF-16 代码单元的偏移量,因此您可以替换

let strIndex = String.UTF16View.Index(encodedOffset: l)

通过

let strIndex = s.utf16.index(s.utf16.startIndex, offsetBy: l)

或使用

let strIndex = String.Index(utf16Offset: l, in: s)

这是在 Swift 5 中引入的 SE-0241 Deprecate String Index Encoded Offsets .

关于Swift 5 : String. UTF16View.Index(encodedOffset: l) 弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55378537/

相关文章:

SwiftUI 获取 ViewModel 中另一个 ViewModel 的值

ios - 不同模块中的相同类名

swift - 如何访问存储在类型为 "Any"的变量中的值

swift - 字符串是未声明的类型?

ios - 如何在 Xcode 11 包管理器中处理 C 文件?

静态表格 View 中的快速自适应单元格高度

swift - 范围结构可以用作 Swift 中的用户输入吗?

ios - 简单地继承 UITouchGestureRecognizer,设置 minimumPressDuration

ios - 使用 Core Data 保存和检索数据 "by date"

ios - 使用 LinkingObjects 时出错(来自类型 :property:) - Use of unresolved identifier 'LinkingObjects'