2016-09-07 34 views
0

什麼即時試圖做的是打印(輸出:西澳大利亞州)如何使用變量具有代碼塊外值

self.stateName = state["ProvinceStateName"] 

detailAddressArr = ["\(userData!["AddressLine1"] as! String)", "\(userData!["AddressLine2"] as! String)", "\(userData!["City"] as! String)", "\(userData!["PostalCode"] as! String)", self.stateName, "\(userData!["CountryCode"] as! String)"] 

但在運行時,它返回任何結果。

這裏是我的代碼

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): 
       do { 

        let json = try JSON(NSJSONSerialization.JSONObjectWithData(successResult.data, options: .MutableContainers)) 

        if json["Status"].string == "OK"{ 
         self.hideHUD() 
         let stateList = json["StateList"].arrayObject! 

         for 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 to connect the 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)"] 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be 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 a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    // Get the new view controller using segue.destinationViewController. 
    // Pass the selected object to the new view controller. 
    } 
    */ 

} 

回答

0

的問題是,要打印Statename的時,它的值是「」。在等待請求的響應之後,塊被異步執行,並且塊之後的行立即執行而不用等待。我認爲,所有你所要做的就是打印行移動代碼塊中或使用屬性觀察員打印Statename的每一次改變

suggestion1:將打印行語句

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): 
      do { 

       let json = try JSON(NSJSONSerialization.JSONObjectWithData(successResult.data, options: .MutableContainers)) 

       if json["Status"].string == "OK"{ 
        self.hideHUD() 
        let stateList = json["StateList"].arrayObject! 

        for state in stateList { 
         let newStateCode = state["ProvinceStateCode"] as! String 

         if newStateCode == stateCode { 
          print(state["ProvinceStateName"]) 
          self.stateName = state["ProvinceStateName"] as! String 
         } 
        } 



    //MOVE PRINT INSIDE THE 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 to connect the server") 
      } 
     case .Failure(let failureResult): 
      self.hideHUD() 
      showErrorMessage(failureResult.nsError.localizedDescription) 
     } 
    } 
} 

Suggestion2:使用財產觀察員

var stateName: String?{ 
    didSet{ 
     print("State name is \(stateName)") 
    } 
} 
+0

建議1: 嘗試打印detailAddressArr時發生新錯誤(索引超出範圍)。 建議2: statename return nil –

相關問題