Home > Software design >  Saving an Array<Color>
Saving an Array<Color>

Time:02-06

I have an array that needs to be formatted as Array. I use the code below to save it throughout my program.

var ScheduledStatusD:Array<Color> {
    get {
        // Get the standard UserDefaults as "defaults"
        let defaults = UserDefaults.standard

      return defaults.stringArray(forKey: "ScheduledStatusD") ?? [Color.gray]
    }
    set (newValue) {
        // Get the standard UserDefaults as "defaults"
        let defaults = UserDefaults.standard

        defaults.set(newValue, forKey: "ScheduledStatusD")
    }
}

My problem is as followed:

Cannot convert value of type '[String]?' to expected argument type '[Color]?'

I've tried change the text .stringArray to .array or .mutableArray, but more problems arose from that. Any solutions?

FYI, the goal here is to have a dynamically stored color array.

CodePudding user response:

Color cannot be saved (directly) in UserDefaults because it's not Property List compliant.

But it has a description property and can be initialized by a string.

So you could map the colors to String and vice versa.

And please name properties with starting lowercase letter

var scheduledStatusD:Array<Color> {
    get {
        return UserDefaults.standard.stringArray(forKey: "ScheduledStatusD")?
            .map{Color($0)} ?? [Color.gray]
    }
    set {
        UserDefaults.standard.set(newValue.map(\.description), forKey: "ScheduledStatusD")
    }
}
  •  Tags:  
  • Related