方法调用请求方法作为参数

时间:2017-07-04 22:03:06

标签: swift function

我对swift很新,所以这可能是一个非常简单的问题,但我正在尝试创建一个在完成时返回列表的方法,但是当我尝试调用该方法时,它说我错过了逃避参数,我不知道如何满足。

以下是方法:

func fillFromFile(completionBlock: @escaping ([Asset_Content]) -> ()) {
    let url = "URL STRING"

    LoadJSONFile(from: url) { (result) in
        // The code inside this block would be called when LoadJSONFile is completed. this could happen very quickly, or could take a long time

        //.map is an easier way to transform/iterate over an array
        var newContentArray = [Asset_Content]()
        for json in result{
            let category = json["BIGCATEGORY"] as? String
            let diagnosis = json["DIAGNOSIS"] as? String
            let perspective = json["PERSPECTIVE"] as? String
            let name = json["NAME"] as? String
            let title = json["Title"] as? String
            let UnparsedTags = json["TAGS"] as? String
            let filename = json["FILENAME"] as? String

            let tagArray = UnparsedTags?.characters.split(separator: ",")
            for tag in tagArray!{
                if(!self.ListOfTags.contains(String(tag))){
                    self.ListOfTags.append(String(tag))
                }
            }

            let asset = Asset_Content(category!, diagnosis!, perspective!, name!, title!, filename!)
            // This is a return to the map closure. We are still in the LoadJSONFile completion block
            newContentArray.append(asset)

        }
        print("return count ", newContentArray.count)
        // This is the point at which the passed completion block is called. 
        completionBlock(newContentArray)
    }
}

这是方法调用:

self.ListOfFiles = fillFromFile()

错误是"缺少参数' completionblock'在电话"

2 个答案:

答案 0 :(得分:2)

您期望使用completionBlock的方法响应的方式如下:

    fillFromFile { (response) in
        self.ListOfFiles = response
    }

像这样你要设置'ListOfFiles'变量,并使用方法中的新变量。

在你的功能返回时,你应该有一个DispatchQueue

DispatchQueue.main.async {
     completionBlock(newContentArray)
}

答案 1 :(得分:0)

请注意fillFromFile函数不返回任何内容。这是一个异步功能。这意味着它独立于调用它的主线控制流来完成它的工作。它几乎立即返回(没有),并在此后的某个未知时间执行其工作。

要获得此函数的结果,您需要给出一个完成处理程序。这是一个闭包,当代码最终完成其工作时将由代码调用。作为此闭包的参数,它将传递工作的结果(Array<Asset_Content>)。

以下是如何满足此方法签名的简单示例:

fillFromFile { (response) in
    print(response)
}

我建议你阅读language guide,特别是关于闭包的部分。