Home > AI > Language > Swift >

change the value of immutable instance

Example:

import Foundation

enum AppDefault: String {
    case APIServer, runMode, homeDirectory, reactHost
    
    var stringValue: String? {
        get {
            return UserDefaults.standard.string(forKey: self.rawValue)
        }
        
        nonmutating set {
            if let newValue = newValue {
                UserDefaults.standard.setValue(newValue, forKey: self.rawValue)
            } else {
                UserDefaults.standard.removeObject(forKey: self.rawValue)
            }
        }
    }
}


// immutable instance
let server = AppDefault.APIServer

// `AppDefault`'s `nonmutating` setter on `stringValue` allows for this work on immutable instances
server.stringValue = "127.0.0.1:4000/"
print(server.stringValue)

Leave a Reply