Ios 导致错误的闭包

Ios 导致错误的闭包,ios,swift,closures,Ios,Swift,Closures,我有两个类,Model和ViewController。我已经从ViewController调用了Model中的一个方法,完成后我需要执行闭包。这就是我所做的: 型号。swift typealias LoginCompletionBlock = () -> Void func registerUser(username : String, emailID email : String, password userPassword : String, profileImage picture

我有两个类,
Model
ViewController
。我已经从
ViewController
调用了
Model
中的一个方法,完成后我需要执行闭包。这就是我所做的:

型号。swift

typealias LoginCompletionBlock = () -> Void

func registerUser(username : String, emailID email : String, password userPassword : String, profileImage picture : UIImage, registrationMethod method : String, onCompletion completion : LoginCompletionBlock)
{
    //Necessary code for an async request
}

// Delegate for getting the registration details
func registrationSucceededForUser(userID : String, withAccessToken token : String)
{
    LoginCompletionBlock() // Error 'LoginCompletionBlock' is not constructible with '()'
}
ViewController.swift
中,我调用了如下函数:

@IBAction func signUp(sender: UIButton)
{
    model.registerUser(usernameTextField.text, emailID: emailTextField.text, password: passwordTextField.text, profileImage: profileImageView.image!, registrationMethod: "normal", onCompletion:{
        () in
        //Perform actions after login
    }) //Error 'Bool' is not a subtype of 'Void'
}

我刚刚开始学习斯威夫特。有谁能指导我如何正确使用闭包以及如何避免这个错误。我需要在闭包和无返回类型中将
Bool
作为参数传递。我没有在代码中包含
Bool
,因为我只是想学习如何使用闭包。

如果需要将Bool传递到闭包中,则必须将typealias从()->Void更改为Bool->Void。此外,需要更改RegistrationSucceedForUser函数,以便将回调作为参数传入。现在,您正在“调用”函数签名,而不是实际的函数

此外,registerUser函数签名中的一些换行符将大大提高可读性

typealias LoginCompletionBlock = Bool -> Void
model.registerUser(usernameTextField.text, emailID: emailTextField.text,
    password: passwordTextField.text, profileImage: profileImageView.image!,
    registrationMethod: "normal", onCompletion: {
         success in
        //Perform actions after login
    })
}

编辑:我已经添加了可能对代码进行的特定修改。可能需要更多信息才能真正理解类型错误的根源。请注意,如果内联闭包的主体由一条语句组成,则可以将其推断为返回值,您可能需要添加换行符和一条空返回语句以满足Void返回类型。

对不起,我没有理解您的意思。你能展示一下正确的代码片段吗?我添加了一个例子。本例中的“success”是函数的一个参数,隐式键入为Bool。好的,让我试试看:)函数调用的错误似乎消失了,但我仍然对如何在成功注册时调用闭包感到困惑。您是否正在试图弄清楚如何实现RegistrationSucceedForUser?在不太了解此处实际发生的情况的情况下,我倾向于假设您的LoginCompletionBlock将在后台线程中被调用,其值指示登录是否成功完成。如果成功完成,您编写的回调应该调用RegistrationSucceedForUser,这可能会更新您的视图。