Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //: Playground - noun: a place where people can play
- import UIKit
- class DataModel {
- // Should be non nil
- var name: String!
- var image: UIImage!
- var defaultImage: UIImage!
- // 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.
- convenience
- init (name n: String, image img: UIImage?, defaultImage dImg: UIImage? = UIImage(named: "testDefaultImageKey")) {
- self.init()
- name = n
- image = img
- defaultImage = dImg
- }
- var modelImage: UIImage? {
- // will return image if image is set and defaultimage if not set
- // '??' is like Bool ? yes : no or '?:' in objc
- return image ?? defaultImage
- }
- }
- var AllDataModel: [DataModel] = []
- // This sample conforms to [String: String]
- let sampleJSON1 = ["name": "name1", "photo": "imageLink1"]
- let sampleJSON2 = ["name": "name2"] // sample with no image link
- let sampleJSON3 = ["photo": "imageLink2"] // sample with no image link
- func addThis(_ sampleJSON: [String: String]) {
- // this will check if 'photo' key has value same for 'name' otherwise will fall to 'else'
- if let imageLink = sampleJSON["photo"], let name = sampleJSON["name"] {
- // fetch this 'imageLink'. when done fetching from the background, convert it to uiimage
- // 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
- let image = UIImage() // the sample fetch converted image
- // init with defaultImage
- let data = DataModel(name: name, image: image)
- // add to your model
- AllDataModel.append(data)
- }else{
- // check for name
- // '??' is like Bool ? yes : no or '?:' in objc
- let name = sampleJSON["name"] ?? "your default name"
- let data = DataModel(name: name, image: nil)
- //let data = DataModel(name: name, image: nil, defaultImage: UIImage(named: "another default image key"))
- // add to your model
- AllDataModel.append(data)
- }
- }
- addThis(sampleJSON1)
- addThis(sampleJSON2)
- addThis(sampleJSON3)
- // log
- for d in AllDataModel {
- d.name
- }
Add Comment
Please, Sign In to add comment