0

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

  • What will be the issue in that you are saving and retrieving without any issue right? – Ganesh Manickam Nov 30 '17 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. –  Nov 30 '17 at 12:07

2 Answers2

1

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()
Indra Mohan
  • 455
  • 4
  • 13
  • Indra Mohan thanks, it's constantly increaring to 1 but i want to get everytime value from numEmails varaiable. –  Nov 30 '17 at 12:29
  • I added that code just for your understanding. Remove that part and put your own logic to calculate the deleted emails. – Indra Mohan Nov 30 '17 at 12:31
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.

Vimal
  • 187
  • 6