条件绑定的初始化程序必须具有可选类型,而不是“()”

时间:2021-12-29 17:05:29

I couldn't solve an "if let" issue in my code. Based on the error it says that I must use an optional type?

我无法在我的代码中解决“if let”问题。根据错误,它说我必须使用可选类型?

@IBAction func operate(sender: UIButton) {

    if userIsInTheMiddleOfTypingANumber{
        enter()
    }
    if let operation = sender.currentTitle {
        if let result = calcModel.performOperation(operation){
            displayValue = result
        }else {
            displayValue = 0
        }
    }
}

1 个解决方案

#1


1  

I suspect that your problem is in this line:

我怀疑你的问题是在这一行:

if let result = calcModel.performOperation(operation)

Your performOperation function's return type is (), or void, which means it doesn't return anything. Chances are, to get the error in the title, your performOperation function on calcModel has the following signature:

您的performOperation函数的返回类型是()或void,这意味着它不返回任何内容。有可能,为了获得标题中的错误,calcModel上的performOperation函数具有以下签名:

func performOperation(operation: String) {

Note the lack of an arrow and type. If you're going to return a result, the signature should be something like this:

注意缺少箭头和类型。如果您要返回结果,签名应该是这样的:

func performOperation(operation: String) -> Int {

You would only need the if let, if you decided to return Int?.

如果你决定返回Int,你只需要if let。

#1


1  

I suspect that your problem is in this line:

我怀疑你的问题是在这一行:

if let result = calcModel.performOperation(operation)

Your performOperation function's return type is (), or void, which means it doesn't return anything. Chances are, to get the error in the title, your performOperation function on calcModel has the following signature:

您的performOperation函数的返回类型是()或void,这意味着它不返回任何内容。有可能,为了获得标题中的错误,calcModel上的performOperation函数具有以下签名:

func performOperation(operation: String) {

Note the lack of an arrow and type. If you're going to return a result, the signature should be something like this:

注意缺少箭头和类型。如果您要返回结果,签名应该是这样的:

func performOperation(operation: String) -> Int {

You would only need the if let, if you decided to return Int?.

如果你决定返回Int,你只需要if let。