Swift 5:不推荐使用String.UTF16View.Index(encodedOffset:l)

net*_*000 5 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
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 6

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

let strIndex = String.UTF16View.Index(encodedOffset: l)
Run Code Online (Sandbox Code Playgroud)

通过

let strIndex = s.utf16.index(s.utf16.startIndex, offsetBy: l)
Run Code Online (Sandbox Code Playgroud)

或使用

let strIndex = String.Index(utf16Offset: l, in: s)
Run Code Online (Sandbox Code Playgroud)

在Swift 5中以SE-0241弃用字符串索引编码偏移量引入。