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

Asked

Viewed 75 times

0

I need to create a variable, idAtual every time I go to add a new department the ID has to be the idAtual + 1, every time I create the idAtual in the Departamentoviewcontroller , he restarts with the value I declared, how do I make this value be constant and just grow ?

2 answers

2

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!)

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.