1

I can save and retrieve deleted mails number (such as like Integer value) in UserDefaults. Suppose if I deleted some more mails then I have to add/increase that saved UserDefaults value and if I retrieve it should come total deleted mails number. ->> Here numEmails is deleted mails number(Integer).

UserDefaults.standard.set(numEmails, forKey: "NumberofMailsDeleted") //Saving
var numMailsDeleted = UserDefaults.standard.integer(forKey: "NumberofMailsDeleted") //Retriving
print("I've deleted \(numMailsDeleted) mails") //Printing` 

I will explain this scenario with other example ->> I want to save vehicles incoming (number of vehicles inside) into the parking area (i.e. the UserDefaults saved value is changing according to the cars incoming). If I retrieve it should come updated value of incoming don't think about outgoing, I don't need outgoing

2
  • What will be the issue in that you are saving and retrieving without any issue right? Commented Nov 30, 2017 at 12:01
  • hi @GaneshManickam, i can save one value but how i can add/increase it's value if i delete more mails after some time. Commented Nov 30, 2017 at 12:07

2 Answers 2

2

You can use the set(Int, forKey: String) method of UserDefaults:

//Get
let deletedMailsCount = UserDefaults.standard.integer(forKey: "NumberofMailsDeleted")
//Update deletedMails count
deletedMailsCount += 1;
//Set
UserDefaults.standard.set(deletedMailsCount, forKey: "NumberofMailsDeleted")
UserDefaults.standard.synchronize()
Sign up to request clarification or add additional context in comments.

2 Comments

Indra Mohan thanks, it's constantly increaring to 1 but i want to get everytime value from numEmails varaiable.
I added that code just for your understanding. Remove that part and put your own logic to calculate the deleted emails.
1
var deletedEmail: Int { get { return UserDefaults.standard.integer(forKey: "emailsDeleted") } set { UserDefaults.standard.set( newValue forKey:"emailsDeleted")} }

Using computed property you can simplify it to something like this. newValue is a keyword you can use inside set property. Do not declare newValue !!. Just try the code and let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.