【问题标题】:Swift: Switch between two optional valuesSwift:在两个可选值之间切换
【发布时间】:2020-08-15 09:31:36
【问题描述】:

我正在尝试实现两个选项值之间的切换:

import UIKit

var numOne: Int?
var numTwo: Int?

func doSomething() {
    switch (numOne, numTwo) {
    case (!nil, nil):
        print("something")
    case (_ == _):
        print("equal")
    default:
        break
    }
}

doSomething()

但是我收到了这个错误:

在第一种情况下,我收到此错误:

'nil' is not compatible with expected argument type 'Bool'

在第二种情况下,我遇到了另一个错误:

Expression pattern of type 'Bool' cannot match values of type '(Int?, Int?)'

我对你们的问题是,我怎样才能设法在 this 和可选值之间生成案例?

非常感谢您的帮助

【问题讨论】:

    标签: ios swift iphone xcode11.4 swift5.2


    【解决方案1】:

    这里没有错;语法不正确。

    你的意思是第一种情况:

    case (.some, .none):
    

    没有!nil 这样的东西。可选项不是布尔值。你也可以写(.some, nil),因为nil 是.none 的别名,但这让人感到困惑。

    你的意思是第二种情况:

    case _ where numOne == numTwo:
    

    这里的重点是您的意思是条件为真 (where ...) 的所有情况 (_)。


    func doSomething() {
        switch (numOne, numTwo) {
        case (.some, .none):
            print("something")
        case _ where numOne == numTwo:
            print("equal")
        default:
            break
        }
    }
    

    【讨论】:

    • 如果我想要这种情况case (.some, .some): 和case _ where numOne == numTwo: 这是numTwo = 1 numOne = 1 的值。只检查第一个案例。
    • 正确。第一个成功的案例是switch 语句中唯一匹配的案例。这就是switch 的工作原理。如果您希望首先应用==,则应先订购。如果你想要两者,你应该使用if,而不是switch。 switch 的重点是恰好执行一个case。
    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多