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

时间:2015-08-06 04:11:25

标签: swift function return

我有一个名为{ "Section":{ "groupId": "1", "groupName": "Personal Details", "SectionSatrtTagName":"Personal Details" "fieldDetails": [ { "isRequired":"required", "labelName":"First Name", "tagType":"input", "tagID":"firstname", "tagName":"firstname", "tagValueBindField":"fname", "tagMaxLength":30, "tagValidationGroup":"personal-details", "isTagVisible":true, "hiddenName":"", "hiddenId":"", "hiddenValue":"", "hiddenBindWidth":"", "isHrRequired":true, "data-dependendValue":"", "tagNameType":"text" }, { "isRequired":"required", "labelName":"Last Name", "tagType":"input", "tagID":"lastname", "tagName":"lastname", "tagValueBindField":"lname", "tagMaxLength":20, "tagValidationGroup":"personal-details", "isTagVisible":true, "hiddenName":"", "hiddenId":"", "hiddenValue":"", "hiddenBindWidth":"", "isHrRequired":true, "data-dependendValue":"", "tagNameType":"text" } ] } } 的函数,它使用SwiftyJSON解析JSON,并将所有有组织的信息(例如标题,大小和时间)返回到getEarthquake() NSMutableArray。我创建了另一个名为info的函数,它在结尾处返回一个名为getEarthquake2()的字符串。但是,在结尾title1它返回nil。有什么方法可以修复其中一个或两个函数,以便getEarthquake2()可以返回我需要的字符串吗? 代码:

title1

1 个答案:

答案 0 :(得分:0)

问题是您从getEarthquake2()调用异步代码。会发生什么是getEarthquake2()不等待getEarthquake的结果并立即返回。

您可以像这样修改代码:

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