ios - How to use variable that have value outside the code block -


what im trying print (output : western australia)

self.statename = state["provincestatename"] 

to

detailaddressarr = ["\(userdata!["addressline1"] as! string)", "\(userdata!["addressline2"] as! string)", "\(userdata!["city"] as! string)", "\(userdata!["postalcode"] as! string)", self.statename, "\(userdata!["countrycode"] as! string)"] 

but when run, return nothing.

here code

class myprofileviewcontroller: baseviewcontroller, uitableviewdelegate, uitableviewdatasource,fbsdkloginbuttondelegate, uiimagepickercontrollerdelegate, uinavigationcontrollerdelegate {       @iboutlet weak var profiletableview: uitableview!     @iboutlet weak var profileimg: uiimageview!     @iboutlet weak var bigidlbl: uilabel!     @iboutlet weak var usernamelbl: uilabel!      let personalarr = ["salutation", "given name", "family name", "date of birth", "nationality", "mobile", "passport"]     var detailpersonalarr = [string]()      let addressarr = ["street 1", "street 2", "city", "post code", "state", "country"]     var detailaddressarr = [string]()      var statename: string = ""      override func viewdidload() {         super.viewdidload()         setupmyprofilebutton()         self.navigationitem.title = "my profile"         showhud()         let userinfo = defaults.objectforkey("userinfo")         bigidlbl.text = "big id : \(userinfo!["customernumber"] as! string)"         usernamelbl.text = "\((userinfo!["firstname"] as! string).capitalizedstring) \((userinfo!["lastname"] as! string).capitalizedstring)"          let userdata = defaults.objectforkey("userdata")          let countrycode = userdata!["countrycode"] as! string          let statecode = userdata!["provincestatecode"] as! string          airasiabigprovider.request(.getstate(countrycode)) { (result) in              switch result {             case .success(let successresult):                 {                      let json = try json(nsjsonserialization.jsonobjectwithdata(successresult.data, options: .mutablecontainers))                      if json["status"].string == "ok"{                         self.hidehud()                         let statelist = json["statelist"].arrayobject!                          state in statelist {                             let newstatecode = state["provincestatecode"] as! string                              if newstatecode == statecode {                                 print(state["provincestatename"])                                 self.statename = state["provincestatename"] as! string                             }                         }                       }else if json["status"].string == "error"{                         self.hidehud()                         showerrormessage("\(json["message"].string!)")                     }                 }                 catch {                     self.hidehud()                     showerrormessage("unable connect server")                 }             case .failure(let failureresult):                 self.hidehud()                 showerrormessage(failureresult.nserror.localizeddescription)             }         }          detailpersonalarr = ["\(userdata!["title"] as! string)", "\(userdata!["firstname"] as! string)", "\(userdata!["lastname"] as! string)", "\(userdata!["dob"] as! string)", "\(userdata!["nationality"] as! string)", "\(userdata!["mobilephone"] as! string)", "\(userdata!["pid"] as! string)"]         detailaddressarr = ["\(userdata!["addressline1"] as! string)", "\(userdata!["addressline2"] as! string)", "\(userdata!["city"] as! string)", "\(userdata!["postalcode"] as! string)", self.statename, "\(userdata!["countrycode"] as! string)"]          // additional setup after loading view.     }      override func didreceivememorywarning() {         super.didreceivememorywarning()         // dispose of resources can recreated.     }      func numberofsectionsintableview(tableview: uitableview) -> int {         return 2     }      func tableview(tableview: uitableview, titleforheaderinsection section: int) -> string? {         switch(section) {         case 0:             return "personal info"         case 1:             return "address"         default:             return ""         }     }       func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {         switch (section) {         case 0:             return personalarr.count         case 1:             return addressarr.count         default:             return 0         }     }      func tableview(tableview: uitableview, heightforrowatindexpath indexpath: nsindexpath) -> cgfloat {         return 40     }      func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {         if indexpath.section == 0 {             let cell = profiletableview.dequeuereusablecellwithidentifier("cell", forindexpath: indexpath) as! customprofiletableviewcell             cell.title.text = personalarr[indexpath.row]             cell.detail.text = detailpersonalarr[indexpath.row]             cell.layoutmargins = uiedgeinsetszero             return cell         }         else {             let cell = profiletableview.dequeuereusablecellwithidentifier("cell", forindexpath: indexpath) as! customprofiletableviewcell             cell.title.text = addressarr[indexpath.row]             cell.detail.text = detailaddressarr[indexpath.row]             cell.layoutmargins = uiedgeinsetszero             return cell         }         fatalerror("unexpected section \(indexpath.section)")     }      func loginbutton(loginbutton: fbsdkloginbutton!, didcompletewithresult result: fbsdkloginmanagerloginresult!, error: nserror!) {         print("user login")     }     func loginbuttondidlogout(loginbutton: fbsdkloginbutton!) {         print("user logged out")     }      /*      // mark: - navigation       // in storyboard-based application, want little preparation before navigation      override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject?) {      // new view controller using segue.destinationviewcontroller.      // pass selected object new view controller.      }      */  } 

the problem printing statename when it's value "". block executed asynchronously after waiting request's response , lines after the block executing without waiting. think have move print line inside code block or use property observer print statename every time changes

suggestion1: move print line statement

override func viewdidload() {     super.viewdidload()     setupmyprofilebutton()     self.navigationitem.title = "my profile"     showhud()     let userinfo = defaults.objectforkey("userinfo")     bigidlbl.text = "big id : \(userinfo!["customernumber"] as! string)"     usernamelbl.text = "\((userinfo!["firstname"] as! string).capitalizedstring) \((userinfo!["lastname"] as! string).capitalizedstring)"      let userdata = defaults.objectforkey("userdata")      let countrycode = userdata!["countrycode"] as! string      let statecode = userdata!["provincestatecode"] as! string      airasiabigprovider.request(.getstate(countrycode)) { (result) in          switch result {         case .success(let successresult):             {                  let json = try json(nsjsonserialization.jsonobjectwithdata(successresult.data, options: .mutablecontainers))                  if json["status"].string == "ok"{                     self.hidehud()                     let statelist = json["statelist"].arrayobject!                      state in statelist {                         let newstatecode = state["provincestatecode"] as! string                          if newstatecode == statecode {                             print(state["provincestatename"])                             self.statename = state["provincestatename"] as! string                         }                     }        //move print inside block     detailpersonalarr = ["\(userdata!["title"] as! string)", "\(userdata!["firstname"] as! string)", "\(userdata!["lastname"] as! string)", "\(userdata!["dob"] as! string)", "\(userdata!["nationality"] as! string)", "\(userdata!["mobilephone"] as! string)", "\(userdata!["pid"] as! string)"]     detailaddressarr = ["\(userdata!["addressline1"] as! string)", "\(userdata!["addressline2"] as! string)", "\(userdata!["city"] as! string)", "\(userdata!["postalcode"] as! string)", self.statename, "\(userdata!["countrycode"] as! string)"]                  }else if json["status"].string == "error"{                     self.hidehud()                     showerrormessage("\(json["message"].string!)")                 }             }             catch {                 self.hidehud()                 showerrormessage("unable connect server")             }         case .failure(let failureresult):             self.hidehud()             showerrormessage(failureresult.nserror.localizeddescription)         }     } } 

suggestion2: use property observers

var statename: string?{     didset{         print("state name \(statename)")     } }  

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -