0

I have created a class in SwiftUI that I use to save UserDefaults:

import Foundation
import SwiftUI
import Combine

class UserSettings: ObservableObject {
    @Published var vin: String {
        didSet {
            UserDefaults.standard.set(vin, forKey: "VIN")
        }
    }
    
    @Published var dateOfPurchase: String {
        didSet {
            UserDefaults.standard.set(dateOfPurchase, forKey: "Date of Purchase")
        }
    }
    
    @Published var currentMiles: String {
        didSet {
            UserDefaults.standard.set(currentMiles, forKey: "Current Miles")
        }
    }
    
    @Published var cell: String {
        didSet {
            UserDefaults.standard.set(cell, forKey: "Cell")
        }
    }
    @Published var email: String {
        didSet {
            UserDefaults.standard.set(email, forKey: "Email")
        }
    }
    
    @Published var tcIsOn: Bool {
        didSet {
            UserDefaults.standard.set(tcIsOn, forKey: "Toyota Care")
        }
    }
    
    init() {

        self.vin = (UserDefaults.standard.object(forKey: "VIN") ?? "") as! String
        self.dateOfPurchase = (UserDefaults.standard.object(forKey: "Date of Purchase") ?? "") as! String
        self.currentMiles = (UserDefaults.standard.object(forKey: "Current Miles") ?? "") as! String
        self.cell = (UserDefaults.standard.object(forKey: "Cell") ?? "") as! String
        self.email = (UserDefaults.standard.object(forKey: "Email") ?? "") as! String
        self.tcIsOn = (UserDefaults.standard.object(forKey: "Toyota Care") ?? false) as! Bool

  }  
}

Basically what I want to do is pull my string value "dateOfPurchase" from UserDefaults convert it to a date format it "MM/dd/yyyy" and then display it in a Text() object. It would seem simple but SwiftUI is not cooperating. My other string values work fine but converting from string --> date is proving problematic. Any insights would be appreciated.

gosborne3
  • 47
  • 1
  • 9
  • Does this answer your question? [Date Format in Swift](https://stackoverflow.com/questions/35700281/date-format-in-swift) – Warren Burton Jun 13 '21 at 19:54
  • Although you may be using this in a SwiftUI app, nothing about your question is SwiftUI-specific. You can use any Swift solution -- it doesn't have to be SwiftUI. – jnpdx Jun 13 '21 at 22:45
  • I think I resolved the problem. I have to initialize a value for the string for the DateFormatter() instance to work. Simply the answer is based on the error "Cannot use instance member 'userSettings' within property initializer; property initializers run before 'self' is available". Thanks for the comments. – gosborne3 Jun 13 '21 at 23:57

0 Answers0