简体   繁体   中英

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 . I created another function called getEarthquake2() that returns a string called title1 at the end. However, at the end getEarthquake2() it returns nil. Is there some way I can fix either or both of the functions so that title1 can return the string that I need? 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() . What happens is that the getEarthquake2() does not wait for result of getEarthquake and returns immediately.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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