【问题标题】:switch statement with ints带整数的 switch 语句
【发布时间】:2018-01-27 11:16:46
【问题描述】:

我正在尝试同时使用两个变量来获得一个简单的 switch 语句,但是我不断收到大量错误,而且我真的不知道如何正确地使用它。我只想知道一个是/不是零,另一个是或不是零。我的代码如下:

    var ptsRemaining: Int?
    var ptsUsed: Int = 0

func updatedButtons() {
        switch (ptsRemaining, ptsUsed) {
        case (0), (0):
            print("do thing 1")
        case (0), (!0):
            print("do thing 2")
        case (!0), (0):
            print("do thing 3")
        case (!0), (!0):
            print("do thing 4")
        default:
            print("error!")
        }
    }

注意我也试过这个:

func updatedButtons() {
        switch (ptsRemaining, ptsUsed) {
        case (0,0):
            print("hello")
        case (0,!0):
            print("hello")
        case (!0,0):
            print("hello")
        case (!0,!0): 
            print("hello")
        default:
            print("Error")
        }
    }

在这两种情况下,我收到的错误如下:

Cannot convert value of type 'Int' to expected argument type 'Bool'
Expression pattern of type 'Int' cannot match values of type 'Int?'

【问题讨论】:

  • 不是case (0, 0):吗?此外,您在 print("error!" 处缺少右括号
  • 我正在查看这个问题*.com/questions/25165123/…,他们做的是 (thing), (thing) 而不是 (thing, thing) 。无论如何都尝试过,但仍然出现错误
  • @dvd.Void 如果你这样写,逗号的意思是“或”。

标签: ios swift xcode


【解决方案1】:

!0 不能说“非 0”。这不是 if 语句。这是模式匹配。

要匹配“anything”的模式,您需要使用_ 又名通配符模式。

switch (ptsRemaining, ptsUsed) {
case (0?, 0):
    print("do thing 1")
case (0?, _):
    print("do thing 2")
case (_, 0):
    print("do thing 3")
default: // you don't need the case of "both not 0"
    print("do thing 4")
}

但是你喊道:“我不想匹配'anything'!我要匹配'not 0'!”。

好吧,switch case 是按顺序匹配的。如果第一种情况不匹配,则一个或多个变量不能为 0!然后我们看看第一个是否为 0,此时我们不关心第二个变量,因为我们知道如果第一个为 0,它不能为 0。第三种情况也是如此。

注意,如果你想把nil当作0,你可以这样做:

switch (ptsRemaining ?? 0, ptsUsed)

然后删除案例中的?s。

【讨论】:

  • ptsRemaining 根据问题是可选的时,这会引发错误
  • @tomsterritt 用例 (0?, 0)
  • @tomsterritt 已编辑。
  • @Sweeper,只是一个简单的问题,您将如何检查负值?像 -_ 或 >0 (但这是布尔值,所以我确定它是错误的
  • @dvd.Void 那么你需要像 shallowThought 在他们的回答中那样使用 where 子句。
【解决方案2】:

您也可以使用where 语句:

var ptsRemaining: Int?
var ptsUsed: Int = 0

func updatedButtons() {
    switch (ptsRemaining, ptsUsed) {
    case (0?, 0):
        print("do thing 1")
    case (0?, let second) where second != 0:
        print("do thing 2")
    case (let first, 0) where first != 0:
        print("do thing 3")
    default:
        print("both not 0")
    }
}

【讨论】:

  • 好吧,我有 4 个 If 语句变得冗长,我认为 switch 语句会是更好的选择
  • 我想赞成在哪里显示包含。但是关于 switch 不是正确的工具的结论太牵强了。
  • 好的,删除了基于意见的结论。
最近更新 更多