【问题标题】:Swift 5: String.UTF16View.Index(encodedOffset: l) deprecatedSwift 5:不推荐使用 String.UTF16View.Index(encodedOffset: l)
【发布时间】:2019-08-18 02:22:27
【问题描述】:

我正在使用此代码在字符串中插入连字符以更好地换行。使用 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
    }
}

【问题讨论】:

    标签: swift swift5


    【解决方案1】:

    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 引入的。

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 2018-03-15
      • 1970-01-01
      • 2018-03-17
      • 2019-08-18
      • 2017-03-26
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多