swift class variable changing in same scope

时间:2016-12-02 05:10:50

标签: swift types properties

I'm new to swift and have been staring at this problem for a while. I'm working on a project to communicate with my Hue Lights. I have a class that creates an Alomofire HTTP request to get the status of my bridge. The results get parsed into an array of strings. Here is my question/problem:

I'm using a type property "currentStatus" to keep track of the last status command. The currentStatus type property is correct inside of the Alamofire.request{} scope, but outside of that scope the type property is reset to an empty array. I have 2 debug print statements (result array count 1 and 2). The 1st one returns the correct count of the array stored in self.currentStatus (in the example I'm running its 62), but the 2nd one returns a count of 0 for the array. Why is the self.currentStatus different in these 2 scopes/contexts?

Here is my code:

class HueJson {
    var hubIPAddress: String = ""
    var currentStatus: [String] = []
    var currentPair: String = ""
    var currentPairList: String = ""
    let checkString = "Hello"

    init() {

    }

    func getCommand(IPAddress: String, Command: String, userName: String, verbose: Bool) -> [String]{
        var jsonStringTrimmed: String = ""

         Alamofire.request("http://\(IPAddress)/api/\(userName)/\(Command)").responseData { response in
            debugPrint("All Response Info: \(response)")
            if let data = response.result.value, let jsonString = String(data: data, encoding: .utf8) {

                jsonStringTrimmed = String(jsonString.characters.filter { !" \n\t\r\"".characters.contains($0) })
                //print("-D- Trimmed String: \(jsonStringTrimmed)")
                self.currentStatus = self.String2Array(currString: jsonStringTrimmed)

                if(verbose) {
                    for i in 0...self.currentStatus.count-1 {
                        print("-D- Main Code: \(self.currentStatus[i])")
                    }
                }
                print("-D- Check String: \(self.checkString)")
                print("-D- result array count 1 = \(self.currentStatus.count)")
            }

        }
        print("-D- result array count 2 = \(self.currentStatus.count)")
        return(self.currentStatus)
    }

0 个答案:

没有答案