无法引用类变量需要' self'关键词

时间:2015-12-29 11:06:08

标签: ios swift

如何在使用self关键字时更新假期?在特定函数外部访问时,变量仍为空。以下代码位于视图控制器类

import Alamofire
import SwiftyJSON
import UIKit    


var holidays = [Holiday]()   

        func loadSampleHoliday(){

                    var holidayObject = Holiday(holidayName: "", holidayDate: "")

                    request(.GET,"URL").responseJSON{
                        response in
                        switch response.result{
                        case .Success(let data):
                            let json = JSON(data)
                            let numberOfHoliday = data.count
                            //var holidayObject : Holiday
                            for (var index = 0; index < numberOfHoliday; ++index){
                                let phDate = json[index]["eventDate"].stringValue
                                let phName = json[index]["eventName"].stringValue
                                holidayObject = Holiday(holidayName: "\(phName)", holidayDate: "\(phDate)")
                                //holidays variable only updated locally
                                // how make the variable updated globally?
                                self.holidays += [holidayObject];

                            }
                            break;
                        case .Failure(let error):
                            print("Request failed");
                            break;
                        }
                    }
                }

1 个答案:

答案 0 :(得分:1)

您的函数loadSampleHoliday()不应直接修改holidays。因为它是异步操作,所以应该添加一个闭包作为此函数的参数,以便能够在异步操作完成后执行代码

所以你可以这样做:

func loadSampleHoliday(completion:([Holiday]) -> ()) {

    request(.GET,"URL").responseJSON {
        response in
        //Create a local array
        var holidays = [Holiday]()

        switch response.result {
        case .Success(let data):
            let json = JSON(data)
            let numberOfHoliday = data.count                
            var holidayObject : Holiday
            for (var index = 0; index < numberOfHoliday; ++index){
                let phDate = json[index]["eventDate"].stringValue
                let phName = json[index]["eventName"].stringValue
                holidayObject = Holiday(holidayName: "\(phName)", holidayDate: "\(phDate)")
                holidays.append(holidayObject)   
            }
            break;
        case .Failure(let error):
            print("Request failed");
            break;
        }
        completion(holidays)
    }
}

然后以这种方式调用它:

loadSampleHoliday { sampleHolidays in
    self.holidays = sampleHolidays
    //Do what you want next
}

现在loadSampleHoliday只负责获取样本假期,您可以使用结果执行所需操作。它更可重用,更具可读性,并确保在执行闭包中的代码时完成异步操作。