Property in Swift - Computed property | Property Observers (WillSet & DidSet)

   Computed property -  Computed properties are part of a property type in Swift.  Stored properties are the most common which save and return a stored value  Computed properties calculate (rather than store) a value. A computed property provides a getter and an optional setter to indirectly access other properties and values. Computed property in swift is an interesting topic as you can write code inside a property in swift. Computed properties are provided by classes, structures, and enumerations but stored properties are provided only by classes and structures. This computed property swift tutorial has some tips on how to use the computed property in the right way and avoid the common mistakes that swift programming beginners do while computed property. Example :- Computed property A Calculate Simple Intrest struct CalculateLoan {      var amount : Int      var rate : Int      var years : Int      var simpleInterest: Int {          get {              return ( amount * rate

Nested JSON Parsing with Alamofire and SwiftyJSON in Swift 4

Build A Simple API (Custom JSON) with Alamofire & SwiftyJSON 


This Full Example helps to design a UIViewController WithOut StoryBoard with a UITableViewController, Custom Cell design to show data ion to api service json, this Tutorial  helps to understand how to use Alamofire with SwiftyJSON to hit an API and fetch results, parse them and show the results in an UITableViewController.

A Nested JSON :- like
/*{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
    "mobile": "+91 0000000000",
    "home": "00 000000",
    "office": "00 000000"
}
}
*/

Web Service api -  https://api.androidhive.info/contacts/ parse the data and show result in tableView.

First create pod file install Alamofire and SwiftyJSON API

Open Terminal -> Then go source folder your create project cd foldername, after type
pod init
open podfile
then edit open podfile
pod 'Alamofile'
pod 'SwiftyJSON'

Then Save podfile and install podfile in terminal - pod install
Then Create a simple Project swift 4 Project Name ContactDetail. Class

AppDelegate.swift - 

Class - 
import UIKit
import Alamofire

@UIApplicationMain
  class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var demoViewController: DemoViewController?
    var navNavigation: UINavigationController?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow.init(frame: UIScreen.main.bounds)
        demoViewController = DemoViewController(nibName: "DemoViewController", bundle: nil)
        navNavigation = UINavigationController(rootViewController: demoViewController!)
        window?.rootViewController = navNavigation
        window?.makeKeyAndVisible()
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

Now Create a Model Class

Model.swift - > 

import Foundation
struct AkhilDemo {
    let name: String!
    let email: String!
    let gender: String!
    let address: String!
    let id: String!
    let phone: Phone

    init(json: [String: Any]) {
        let Name =  json["name"] as? String
        let Email =  json["email"] as? String
        let Gender =  json["gender"] as? String
        let Address =  json["address"] as? String
        let Id =  json["id"] as? String
        let phoneDict = json["phone"] as? [String: Any]
        let phone = Phone(json: phoneDict!)
        
        self.name = Name
        self.email = Email
        self.gender = Gender
        self.address = Address
        self.id = Id
        self.phone = phone
        
        //self.phone = json["phone"] as? [String]
    }
struct Phone {
        let mobile: String!
        let home: String!
        let office: String!
        
        init(json: [String: Any])  
            let Mobile = json["mobile"] as? String
            let Home = json["home"] as? String
            let office = json["office"] as? String
            
            self.home = Home
            self.mobile = Mobile
            self.office = office
            
        }
    }
}

--Edit ViewController Class - ContactDetailViewController.swift
Import Alamofile & SwiftyJSON and design tableView  with Custom Cell - pCell.swift - 


ContactDetailViewController.swift -> 

import UIKit
import Alamofire
import SwiftyJSON
class DemoViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
   
    @IBOutlet var tableView: UITableView!
    var akhildemo: [AkhilDemo] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "pCell", bundle: nil), forCellReuseIdentifier: "Cell")
        getJSON()
        // Do any additional setup after loading the view.
    }
    func getJSON(){ Alamofire.request("https://api.androidhive.info/contacts/").responseJSON(completionHandler: {(response) in
        if response.value != nil{
            //print(response)
            if let json = response.result.value as? [String: Any]{
                if let contact = json["contacts"] as? [[String: Any]]{
                    for dic in contact {
                        let contacts = AkhilDemo.init(json: dic)
                        self.akhildemo.append(contacts)
                    }
                    self.tableView.reloadData()
                }
            }
            
        } else{
            print("error")
        }
        
    })
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.akhildemo.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! pCell
        cell.idLabel.text = self.akhildemo[indexPath.row].id
        cell.nameLabel.text = self.akhildemo[indexPath.row].name
        cell.emailLabel.text = self.akhildemo[indexPath.row].email
        cell.adressLabel.text = self.akhildemo[indexPath.row].address
        cell.ageLabel.text = self.akhildemo[indexPath.row].gender
        cell.phoneLabel.text = self.akhildemo[indexPath.row].phone.mobile
        
        return cell
    }

}


Custom Cell - pCell.swift - 


import UIKit

class pCell: UITableViewCell {
    
    @IBOutlet var idLabel: UILabel!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var emailLabel: UILabel!
    @IBOutlet var ageLabel: UILabel!
    @IBOutlet var adressLabel: UILabel!
    @IBOutlet var phoneLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
   override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


Output- 









Comments