首页 文章

闭包导致错误Swift

提问于
浏览
0

我有两个班, ModelViewController . 我在 ViewController 中调用了 Model 中的一个方法,完成后我需要执行闭包 . 这就是我所做的:

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

我刚刚开始使用swift . 任何人都可以指导我如何正确使用闭包,我该如何避免这个错误 . 我需要在闭包中传递 Bool 作为参数而没有返回类型 . 我没有在代码中包含 Bool ,因为我只是想学习如何使用闭包 .

1 回答

  • 1

    如果你需要将一个bool传递给闭包,你必须将typealias从() - > Void更改为Bool - > Void . 此外,您需要更改registrationSucceededForUser函数,以便将回调作为参数传入 . 现在,您正在“调用”函数签名,而不是实际函数 .

    此外,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返回类型 .

相关问题