从 AVSpeechSynthesisVoice 获取国家列表

Get list of countries from AVSpeechSynthesisVoice

我正在尝试获取在 AVSpeechSynthesisVoice 中找到的 Region Code,而不是例如: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 ?? ""))"
}

谢谢!

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

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 ?? ""))"
}