NEW: Learn SwiftData for free with my all-new book! >>

SOLVED: Can't save [Character] to UserDefaults

Forums > Swift

OK, so here's a stripped-down version of the code that's having problems

import Foundation

class MyClass {
    static private(set) var characterArray: [Character] = []

    init() {
        let defaults = UserDefaults.standard

        MyClass.characterArray = defaults.array(forKey: "characterArray") as? [Character] ?? [Character]()

    func saveDefaults() {
        let defaults = UserDefaults.standard

        defaults.set(MyClass.characterArray, forKey: "characterArray") // Error occurs here

    func doStuff() {
        let character = Character("字")

Near as I can tell I've followed all the instructions on how to store and recall arrays in UserDefaults per here, however when I try to run my program I get the following:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object ( "\"\U9811\"" ) for key characterArray' terminating with uncaught exception of type NSException

Attempt to set a non-property-list object ( "\"\U9811\"" ) as an NSUserDefaults/CFPreferences value for key characterArray 2020-09-29 22:38:54.249117-0400 Jouyou Study[29347:2368675] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object ( "\"\U9811\"" ) for key characterArray'

I have other static properties that are Ints and Strings that are storing fine, so I don't think that's the cause. Is the issue perhaps because we're storing Unicode characters (specifically, kanji characters) in the array?

I've tried working around it by saving it as an object to UserDefaults, however when I do that it flips out because Array, Set, Character, etc., do not conform to Codable, apparently? I've spent 3 hours on this and I'm starting to lose track of some things.

Thanks in advance for any insights!


Character is not one of the types you can store in UserDefaults, so you can't store an array of them either. You would need to convert it to a type that can be stored in UserDefaults, like Data or String.


oops, double post!


That's exactly what it was. Kind of feels weird, since Character is a more primitive type than String, but that's how it is, I guess.



Hacking with Swift is sponsored by Swiftable

SPONSORED An iOS conference hosted in Buenos Aires, Argentina – join us for the third edition from November 29th to December 1st!

Get your ticket

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.