You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS 16+如何替代废弃的Locale.isoRegionCodes获取ISO-3166-alpha2国家码?

iOS 16+ Locale国家码适配解决方案

你遇到的region.identifier返回001的问题,是因为Locale.Region.isoRegions包含了所有ISO标准定义的区域,其中包括“世界(001)”“大洲”这类聚合区域,并非都是单独的国家/地区。

获取两位字母国家码的正确方式

不需要手动映射ISO-3166-alpha2代码,新API本身支持直接获取,只需两步:

  1. 过滤掉非国家类型的区域
  2. 使用region.code.rawValue获取两位字母码

修正后的代码示例:

if #available(iOS 16, *) {
    let countryList = Locale.Region.isoRegions
        // 过滤仅保留国家类型的区域
        .filter { $0.code.category == .country }
        .compactMap { region -> CustomCountry? in
            // 直接获取两位字母ISO国家码
            guard let alpha2Code = region.code.rawValue as? String else {
                return nil
            }
            // 可选:获取当前语言下的国家名称,提升用户体验
            let localizedName = Locale.current.localizedString(forRegionCode: alpha2Code) ?? alpha2Code
            return CustomCountry(value: localizedName, key: alpha2Code)
        }
        .sorted(by: { $0.value < $1.value })
} else {
    // 旧版本兼容逻辑,沿用原有API
    let countryList = Locale.isoRegionCodes
        .compactMap { code -> CustomCountry? in
            let localizedName = Locale.current.localizedString(forRegionCode: code) ?? code
            return CustomCountry(value: localizedName, key: code)
        }
        .sorted(by: { $0.value < $1.value })
}

关键细节说明

  • $0.code.category == .country:通过区域分类过滤,排除“世界”“大洲”等非国家区域,避免出现001这类非国家码。
  • region.code.rawValue:Locale.Region.Code的rawValue就是标准的两位字母ISO-3166-alpha2代码,和旧APILocale.isoRegionCodes返回的格式完全一致。
  • 本地化名称获取:使用Locale.current.localizedString(forRegionCode:)可以拿到当前系统语言下的国家名称,比直接用代码更友好。

关于手动映射的疑问

完全不需要手动维护ISO-3166-alpha2映射表,新API已经封装了标准的国家码和本地化信息,只要正确过滤和调用属性就能得到所需结果。

内容的提问来源于stack exchange,提问作者Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 04:14:59