User defaults do not persist on Linux

I am new to Swift so apologies if I'm missing something obvious.

I'm building a small command line tool for Linux, mostly as an exercise for myself. I want a way of persisting some options that can be set via the tool and thought UserDefaults might be a good fit. The code boils down to this:

import Foundation

func store(key: String, value: String) {
    UserDefaults.standard.set(value, forKey: key)
    print("\"\(UserDefaults.standard.string(forKey: key) ?? "No Value Found")\" was stored for key \"\(key)\"")

func retrieve(key: String) {
    let value = UserDefaults.standard.string(forKey: key) ?? "No Value Found"

When calling store() and retrieve() in the same app session, UserDefaults work as expected on both macOS and Linux.

When calling store() and retrieve() in separate app sessions, UserDefaults work as expected on macOS, but retrieve() fails on Linux, reporting "No Value Found".

I came across this post and have checked the contents of /usr/local/etc and $XDG_CONFIG_DIR for .plist files. Neither location contains such a file.

My Linux dev setup is a VM with stock Ubuntu 20.04 server and Swift 5.3 installed using the guide on - Getting Started.

I could of course persist data using something other than UserDefaults, though I thought it was a neat way of making the app compile cross platform without needing to worry about the location of the data.


... three years later, still not working. Maybe it's time to go bug hunting :man_shrugging:t3:

Foundation is being re-written (GitHub - apple/swift-foundation: The Foundation project) so it's probably not worth tracking down bugs in the current version of Foundation... Alas it seems that UserDefaults isn't in the first tranche of API to be covered in the rewrite.

I couldn't see a bug recorded for this in the current version of Foundation's GitHub page though...

I've filed one: UserDefaults don't persist on Linux · Issue #4837 · apple/swift-corelibs-foundation · GitHub

1 Like