Search code examples
iosswiftfoundation

When could the user's Locale.current.region be nil?


The locale region is optional from Foundation. It is my understanding that this property is read from the device under iOS Settings > General > Language & Region > Region.

What is the possible scenarios that the region property is nil; why is it optional?


Solution

  • It is my understanding that this property is read from the device under iOS Settings > General > Language & Region > Region

    Well, that would be Locale.current, but that is not the only instance of Locale instance there can be. You can create your own locales.

    More accurately, region is:

    This property corresponds to the rg key of the Unicode BCP 47 extension. For locale instances created with the rg specifier (such as en-GB@rg=US), or with a custom Locale.Components, this property represents the custom region. Otherwise, it represents the language’s region.

    I tried setting Locale.Components.region to nil, but the Locale created this way still has the default region of the language:

    var components = Locale.Components(languageCode: .english)
    components.region = nil
    let locale = Locale(components: components)
    print(locale.region) // US
    

    If the Locale.Language does not belong to any region though, then region would be nil. And such Locale.Languages do exist! For example:

    // zxx - no linguistic content
    let unidentified = Locale(languageCode: .unidentified)
    print(unidentified.region) // nil
    
    // mul - multiple languages
    let multiple = Locale(languageCode: .multiple)
    print(multiple.region) // nil
    

    So region has to be optional at least because of the mul and zxx "languages", as required in BCP 47.