NYAccountManager.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // NYAccountManager.swift
  3. // JiaPeiManage
  4. //
  5. // Created by Ning.ge on 2023/7/28.
  6. //
  7. import Foundation
  8. struct Account {
  9. let username: String
  10. let password: String
  11. }
  12. class NYAccountManager {
  13. private var accounts: [Account] = []
  14. private let maxAccountCount = 5
  15. func addAccount(username: String, password: String) {
  16. let account = Account(username: username, password: password)
  17. if accounts.count < maxAccountCount {
  18. accounts.append(account)
  19. } else {
  20. accounts.removeFirst()
  21. accounts.append(account)
  22. }
  23. saveAccounts()
  24. }
  25. func deleteAccount(at index: Int) {
  26. guard index >= 0 && index < accounts.count else {
  27. return
  28. }
  29. accounts.remove(at: index)
  30. saveAccounts()
  31. }
  32. func getAccounts() -> [Account] {
  33. return accounts
  34. }
  35. private func saveAccounts() {
  36. // Convert the accounts array to a JSON representation and save it to UserDefaults or any other persistent storage of your choice
  37. let jsonEncoder = JSONEncoder()
  38. // if let data = try? jsonEncoder.encode(accounts) {
  39. // UserDefaults.standard.set(data, forKey: "savedAccounts")
  40. // }
  41. }
  42. private func loadAccounts() {
  43. // Load the accounts from UserDefaults or any other persistent storage
  44. // if let data = UserDefaults.standard.data(forKey: "savedAccounts") {
  45. // let jsonDecoder = JSONDecoder()
  46. // if let savedAccounts = try? jsonDecoder.decode([Account].self, from: data) {
  47. // accounts = savedAccounts
  48. // }
  49. // }
  50. }
  51. init() {
  52. loadAccounts()
  53. }
  54. }