简体   繁体   English

Swift:如何将函数类型值设置为可选变量?

[英]Swift: how to set function type value to optional variable?

I want to use function as a completion for another function, when it's needed. 我想在需要时使用函数作为另一个函数的完成。 But I have a trouble that best described with code: 但是我遇到了最好用代码描述的麻烦:

...{
   var myCompletion : (() -> Void)? = nil
   if condition {
       myCompletion = myCompletionFunction() // <==========problem here
   }
   someMethodThatCouldHaveCompletion(myCompletion)
   ...
}

func someMethodThatCouldHaveCompletion(completion: (() -> Void)?){
...
}

func myCompletionFunction() {
...
}

I have an error: Cannot assign a value of type '()' to a value of type '(()->Void)?' 我有一个错误: Cannot assign a value of type '()' to a value of type '(()->Void)?'

I tried to add as! (() -> Void)? 我试着添加as! (() -> Void)? as! (() -> Void)? after setting function to myCompletion variable, but receive another error Cannot downcast from '()' to a more optional type '(()->Void)?' 将函数设置为myCompletion变量后,但收到另一个错误Cannot downcast from '()' to a more optional type '(()->Void)?'转发Cannot downcast from '()' to a more optional type '(()->Void)?'

So, is there a way to solve it? 那么,有没有办法解决它? I have a sense that I miss something with completion: (() -> Void)? 我有一种感觉,我错过了completion: (() -> Void)?东西completion: (() -> Void)? type. 类型。

The type of myCompletion is fine, the problem is here: myCompletion的类型很好,问题在于:

myCompletion = myCompletionFunction()

You aren't assigning myCompletion to myCompletionFunction ; 您没有将myCompletion分配给myCompletionFunction ; you're calling myCompletionFunction and assigning it's return value to myCompletion , causing the type mismatch. 你正在调用myCompletionFunction并将它的返回值myCompletion ,导致类型不匹配。

Change that line to: 将该行更改为:

myCompletion = myCompletionFunction

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

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