【问题标题】:Initializer for conditional binding must have Optional type, not"()"条件绑定的初始化器必须具有 Optional 类型,而不是“()”
【发布时间】:2016-06-25 17:09:03
【问题描述】:

我无法解决我的代码中的“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
        }
    }
}

【问题讨论】:

    标签: swift xcode7.2


    【解决方案1】:

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

    if let result = calcModel.performOperation(operation)
    

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

    func performOperation(operation: String) {
    

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

    func performOperation(operation: String) -> Int {
    

    如果您决定返回Int?,则只需要if let

    【讨论】:

    • 谢谢乔希!我想我发现了错误。我忘记让 performOperation 返回值。
    • 不客气,欢迎来到 Stack Overflow ?。当某个答案解决了您的问题时,您可以使用旁边的灰色勾号按钮将其标记为已接受的答案,有些人也会选择投票。
    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2021-04-26
    • 2016-01-27
    相关资源
    最近更新 更多