It may seem complicated, but it’s quite simple: Each time you access the user’s own counter defaults, add 1 to the result, save the new value in the user’s preferences (Userdefaults) and then return the value of your variable
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 your app preferences (Userdefaults) (including counter)
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)