I need to create a variable, idAtual every time I add a new department, the ID must be idAtual + 1 , every time I create idAtual in the DepartmentViewController, it restarts with the value I declared, how do I make that value constant and just grow?
I need to create a variable, idAtual every time I add a new department, the ID must be idAtual + 1 , every time I create idAtual in the DepartmentViewController, it restarts with the value I declared, how do I make that value constant and just grow?
It may seem complicated, but it's quite simple: Each time you access the counterfactor's property of user defaults, add 1 to the result, save the new value to the UserDefaults, and then return the value of your < p>
extension UserDefaults {
static var counter: Int {
let counter = UserDefaults.standard.integer(forKey: "counter") + 1
UserDefaults.standard.set(counter, forKey: "counter")
return counter
}
}
let id1 = UserDefaults.counter // 1
let id2 = UserDefaults.counter // 2
let id3 = UserDefaults.counter // 3
print("id1:", id1, "\nid2:", id2,"\nid3:", id3)
id1: 1
id2: 2
id3: 3
To reset the preferences (UserDefaults) of your app (including the counter)
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)