如何使用在代码块之外具有值的变量

时间:2016-09-07 11:57:18

标签: ios swift

我想要做的是打印这个(输出:西澳大利亚州)

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.
     }
     */

}

1 个答案:

答案 0 :(得分: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)
        }
    }
}

建议2:使用属性观察者

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