apple / swift-foundation

The Foundation project
Apache License 2.0
2.36k stars 150 forks source link

Locale.current returns en_US even when the user's locale settings is different on Linux #717

Open jasaldivara opened 1 year ago

jasaldivara commented 1 year ago

I'm using Swift Language on a Linux system

My OS Distro is Fedora 37 on an ARM64 CPU I'm using Swift version 5.7.3 (swift-5.7.3-RELEASE) from the Fedora repos

I'm using GNOME desktop and have set my user session language to spanish, and my region to Mexico

When I run the locale command on a terminal, I get this output:

LANG=es_ES.UTF-8
LC_CTYPE="es_ES.UTF-8"
LC_NUMERIC=es_MX.UTF-8
LC_TIME=es_MX.UTF-8
LC_COLLATE="es_ES.UTF-8"
LC_MONETARY=es_MX.UTF-8
LC_MESSAGES="es_ES.UTF-8"
LC_PAPER=es_MX.UTF-8
LC_NAME="es_ES.UTF-8"
LC_ADDRESS="es_ES.UTF-8"
LC_TELEPHONE="es_ES.UTF-8"
LC_MEASUREMENT=es_MX.UTF-8
LC_IDENTIFICATION="es_ES.UTF-8"
LC_ALL=

But when I reference Locale.current, either on a compiled program, or from the Swift REPL, I get a "en_US" Locale. For example, if I run print (Locale.current.identifier) on the REPL, i get:

en_US

I think the expected behavior is that Locale.current returns the same locale from my user settings. Or am I missing something?

All3yp commented 1 year ago

Maybe I'm wrong, It seems that Swift is not using the locale settings from your computer. Instead, it is defaulting to the "en_US" locale. I think this happened because Swift may not be aware of your user session settings or it may not be able to access them for some unknown reason. To fix this, you can set the locale explicitly in your Swift code using the Locale(identifier: String) initializer. For example, you can set the locale to es_ES like this example:

let myLocale = Locale(identifier: "es_ES”)

Or, maybe, you can try setting the LC_ALL environment variable to your desired locale before running your Swift program. For example, you can set the environment variable to es_ES.UTF-8 like this:

export LC_ALL=es_ES.UTF-8

let me know if this works.

jasaldivara commented 1 year ago

Hi Sorry for taking a long time to answer

let myLocale = Locale(identifier: "es_ES”)

The problem is that I want my program to take the locale from the user session settings, and not to be hardcoded

export LC_ALL=es_ES.UTF-8

This didn't work. Even after setting that environment variable, when I run print (Locale.current.identifier), it still prints an english based locale: en_US

However, I found a workaround for my particular use case: Since I'm working with the SwiftGtk environment, I'm using GLib's getLanguageNames function to get the user session locale:

let langs = getLanguageNames()!
let locale = Locale(identifier: String(cString: langs[0]!))