nferocious76

Swift iOS Development question

Nov 2nd, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4.  
  5.  
  6. class DataModel {
  7.  
  8. // Should be non nil
  9. var name: String!
  10. var image: UIImage!
  11. var defaultImage: UIImage!
  12.  
  13. // Here we create a convenice init with a value for defaultImageKey. From this init we will have two types of init upon calling an init class. see below example.
  14. convenience
  15. init (name n: String, image img: UIImage?, defaultImage dImg: UIImage? = UIImage(named: "testDefaultImageKey")) {
  16. self.init()
  17.  
  18. name = n
  19. image = img
  20. defaultImage = dImg
  21. }
  22.  
  23. var modelImage: UIImage? {
  24. // will return image if image is set and defaultimage if not set
  25. // '??' is like Bool ? yes : no or '?:' in objc
  26. return image ?? defaultImage
  27. }
  28. }
  29.  
  30. var AllDataModel: [DataModel] = []
  31.  
  32. // This sample conforms to [String: String]
  33. let sampleJSON1 = ["name": "name1", "photo": "imageLink1"]
  34. let sampleJSON2 = ["name": "name2"] // sample with no image link
  35. let sampleJSON3 = ["photo": "imageLink2"] // sample with no image link
  36.  
  37. func addThis(_ sampleJSON: [String: String]) {
  38.  
  39. // this will check if 'photo' key has value same for 'name' otherwise will fall to 'else'
  40. if let imageLink = sampleJSON["photo"], let name = sampleJSON["name"] {
  41.  
  42. // fetch this 'imageLink'. when done fetching from the background, convert it to uiimage
  43. // insight: don't store image data if it will be use immediately. why? you'll block the main thread converting this to uiimage or will take some time before displaying to user
  44.  
  45. let image = UIImage() // the sample fetch converted image
  46. // init with defaultImage
  47. let data = DataModel(name: name, image: image)
  48.  
  49. // add to your model
  50. AllDataModel.append(data)
  51.  
  52. }else{
  53. // check for name
  54. // '??' is like Bool ? yes : no or '?:' in objc
  55. let name = sampleJSON["name"] ?? "your default name"
  56.  
  57. let data = DataModel(name: name, image: nil)
  58. //let data = DataModel(name: name, image: nil, defaultImage: UIImage(named: "another default image key"))
  59.  
  60. // add to your model
  61. AllDataModel.append(data)
  62. }
  63. }
  64.  
  65. addThis(sampleJSON1)
  66. addThis(sampleJSON2)
  67. addThis(sampleJSON3)
  68.  
  69. // log
  70. for d in AllDataModel {
  71. d.name
  72. }
Add Comment
Please, Sign In to add comment