How to create a variable that only increases equal to an ID in swift 4?

0

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?

    
asked by anonymous 21.08.2018 / 21:40

2 answers

2

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!)
    
31.08.2018 / 01:04
0

You young uai that save this value, and after the app close keep it and that?

If it is only increment and only here

Declare

var id = 0

Increment

id = id + 1

If you want to save search for UserDefaults you should solve

link

link

    
28.08.2018 / 15:20