Advertisement
Guest User

Untitled

a guest
Feb 24th, 2019
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. //
  2. // User.swift
  3. // TableViewDemo
  4. //
  5. // Created by Bilguun Batbold on 22/2/19.
  6. // Copyright © 2019 ISEM. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. public struct User {
  12. let name: String
  13. let gender: String
  14. let email: String
  15. }
  16.  
  17. public class UserManager {
  18.  
  19. //set array of users (in reality this is usually from a network call
  20. public var users: [User] = [User(name: "Albert", gender: "Male", email: "albert@gmail.com"), User(name: "Bob", gender: "Male", email: "bob@gmail.com"), User(name: "Celine", gender: "Female", email: "celine@gmail.com"), User(name: "Derrick", gender: "Male", email: "derrick@gmail.com"), User(name: "Aldwin", gender: "Male", email: "aldwin@gmail.com")]
  21.  
  22. private var userSection = [String]()
  23. private var userDictionary = [String:[User]]()
  24.  
  25. //invoke sort user function when initialized
  26. init() {
  27. sortUser()
  28. }
  29.  
  30. //this functions goes through each user and sets the first letter as a key. It then populates the list of users with the same key
  31. // this way we will end up with dictionary of users under their respecive alphabetical order
  32. private func sortUser() {
  33. for user in users {
  34. let key = "\(user.name[user.name.startIndex])".uppercased()
  35. if var userValue = self.userDictionary[key] {
  36. userValue.append(user)
  37. } else {
  38. self.userDictionary[key] = [user]
  39. }
  40. self.userSection = [String](self.userDictionary.keys).sorted()
  41. }
  42. }
  43.  
  44. public var userSections: [String] {
  45. return userSection
  46. }
  47.  
  48. public var userDictionaries: [String:[User]] {
  49. return userDictionary
  50. }
  51.  
  52. //return total count
  53. public var userCount: Int {
  54. return users.count
  55. }
  56.  
  57. public func addUser(user: User) {
  58. users.append(user)
  59. }
  60.  
  61. //get user
  62. public func getUser(at index:Int) -> User {
  63. return users[index]
  64. }
  65.  
  66. public func deleteUser(at index: Int) {
  67. users.remove(at: index)
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement