带有完成处理程序和返回的Swift函数

时间:2018-08-28 16:10:53

标签: swift

如何使Swift函数返回值并同时具有完成处理程序?这个想法是该函数首先返回一个临时结果,然后返回最终结果。像这样:

func method(completion: (Int) -> ()) {
    return 2
    ... some processing ...
    completion(3)
}

let a:Int = method(completion: { (new) -> Void in
  a = new
})

2 个答案:

答案 0 :(得分:1)

你把它倒过来了。您必须使用 completion 处理程序来生成中级结果,并使用 return 来生成最终结果。调用return以后,控件就会从函数中消失。

func method(completion: (Int) -> ()) -> Int {
    completion(1)
    //
    //
    completion(2)
    //
    //
    return 3
}

并像这样处理结果。

let a: Int = method(completion: { (new) -> Void in
    print(new)
})
print(a)

OR

改为具有两个 完成处理程序

func foo(provisionalCompletion: (Int) -> (), finalCompletion: (Int) -> ()) {
    provisionalCompletion(someValue)
    //
    //
    provisionalCompletion(someValue)
    //
    //
    finalCompletion(finalValue)
}

您可以调用它并处理中间结果和最终结果。

foo(completion: { (provisionalValue) in
    // Handle provisional value
}) { (finalValue) in
    // Handle final value
}

第二种方法更灵活,但有时也会造成混淆。您只有在达到最终结果时才必须谨慎地调用最终完成。或者您可以在每个决赛之后添加回报。但是再一次,您必须确保达到最终结果。

答案 1 :(得分:1)

您很近。您需要启动一些后台进程(完成处理程序的整个过程),然后然后执行return

func method(completion: @escaping (Int) -> ()) -> Int {
    DispatchQueue.global().async {
        var x = 0
        for y in 0...10_000 {
            x += y
        }

        completion(3)
    }

    return 2
}

var aRes = 0
aRes = method(completion: { (new) -> Void in
    aRes = new
    print("2", aRes)
})
print("1", aRes)

这将导致:

  

1 2
  2 3

第二行在延迟后出现。

请注意,您不能这样做:

var aRes = method(completion: { (new) -> Void in
    aRes = new
    print("2", aRes)
})

这将导致错误“变量在其自身的初始值内使用”。

相关问题