简体   繁体   English

Swift:如何修复超出范围的函数返回nil

[英]Swift: how to fix function returning nil when out of scope

I have a function called getEarthquake() that parses JSON using SwiftyJSON and returns all of the organized information (such as title, magnitude, and time) into an NSMutableArray called info . 我有一个名为getEarthquake()的函数,该函数使用SwiftyJSON解析JSON,并将所有组织的信息(例如标题,大小和时间)返回到一个名为infoNSMutableArray I created another function called getEarthquake2() that returns a string called title1 at the end. 我创建了另一个名为getEarthquake2()函数,该函数getEarthquake2()返回一个名为title1的字符串。 However, at the end getEarthquake2() it returns nil. 但是,最后getEarthquake2()返回nil。 Is there some way I can fix either or both of the functions so that title1 can return the string that I need? 有什么办法可以修复其中一个或两个函数,以便title1可以返回我需要的字符串? The code: 编码:

var info = NSMutableArray()

func getEarthquake(completion: (results : NSMutableArray) ->Void) {
    DataManager.getEarthquakeDataFromFileWithSuccess {
        (data) -> Void in
        let json = JSON(data: data)
        if var JsonArray =  json.array {
            JsonArray.removeAtIndex(0)
            for appDict in JsonArray {
                var mag: String? = appDict["mag"].stringValue
                var title: String? = appDict["title"].stringValue
                var time: String? = appDict["time"].stringValue
                var information = AppModel(title: title, magnitude: mag, time1: time)
                info.addObject(information)
           //     info.removeRange(3...48)

                completion(results: info)
            }
        }

    }
}
func getEarthquake2() -> String? {
    var title1: String?

    getEarthquake { (info) in
        let title = (info[0] as AppModel).title
        title1 = title // title1 is not nil
    }

    return title1 // here title1 is nil
}

The problem is that you are calling asynchronous code from getEarthquake2() . 问题是您正在从getEarthquake2()调用异步代码。 What happens is that the getEarthquake2() does not wait for result of getEarthquake and returns immediately. 发生的情况是getEarthquake2()不等待getEarthquake结果并立即返回。

You could modify your code like this: 您可以这样修改代码:

func getEarthquake2() -> String? { // <- do not return anything
    var title1: String? // <- remove

    getEarthquake { (info) in
        let title = (info[0] as AppModel).title
        title1 = title // title1 is not nil
        // <- add code that uses title here.
    }

    return title1 // here title1 is nil // <- remove. This method returns before the getEarthquake has a chance to set title1. 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM