1

我试图Region Code在 AVSpeechSynthesisVoice 而不是 eg:中找到en-GB

我的目标输出如下

在此处输入图像描述

这是我当前的代码,虽然它有效,但我觉得必须有一个更优雅的解决方案,从我读到的内容中,-可能会产生某些语言的错误

let speechVoices = AVSpeechSynthesisVoice.speechVoices()

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let language = Locale.current.localizedString(forLanguageCode: speechVoices[row].language)!
    let languageCode = speechVoices[row].language

    var regionCodeArray = languageCode.split(separator: "-") // FIXME: buggy may break
    let regionCode = regionCodeArray.removeLast()

    // Must be a more elegant way to get RegionCode
    let country = Locale.current.localizedString(forRegionCode: String(regionCode))

    return "\(language) (\(country ?? ""))"
}

谢谢!

4

1 回答 1

1

所以我想到了另一个不需要拆分的替代方案,这就是我得到的,但我欢迎替代答案,或者在我学习和寻求改进时对我的代码发表评论

let speechVoices = AVSpeechSynthesisVoice.speechVoices()

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let language = Locale.current.localizedString(forLanguageCode: speechVoices[row].language)!
    let languageCode = speechVoices[row].language

    var regionCode:String = ""
    for region in Locale.isoRegionCodes {
        // Test if provided region codes has voices or not
        if languageCode.contains(region) {
            regionCode = region
        }
    }

    let country = Locale.current.localizedString(forRegionCode: String(regionCode))

    return "\(language) (\(country ?? ""))"
}
于 2020-06-11T13:44:56.403 回答