You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中使用双变量Int(含可选类型)编写switch语句报错求助

解决Swift中双变量Switch语句的语法问题

我来帮你搞定这个switch语句的问题~你的代码里主要有三个核心错误,我先帮你拆解,再给出正确的写法:

错误原因分析

  • 可选类型不匹配:ptsRemaining是Int?(可选整数),但你直接用0(非可选Int)去匹配,就会出现Expression pattern of type 'Int' cannot match values of type 'Int?'的错误,Swift不允许直接把可选类型和非可选类型做模式匹配。
  • 非零判断语法错误:Swift里没有!0这种写法,这是C语言的逻辑,判断非零得用where分句或者绑定变量后判断不等于0。
  • 元组匹配语法错误:你第一种写法里的(0), (0)是两个独立的case,不是匹配元组(ptsRemaining, ptsUsed)同时为(0,0),正确的元组匹配格式应该是(0, 0)。

正确写法(处理可选类型nil的情况)

如果需要处理ptsRemaining为nil的场景,完整的switch写法应该是这样:

var ptsRemaining: Int?
var ptsUsed: Int = 0

func updatedButtons() {
    switch (ptsRemaining, ptsUsed) {
    case (.some(0), 0):
        print("do thing 1: 两者都为0")
    case (.some(0), let used where used != 0):
        print("do thing 2: ptsRemaining为0,ptsUsed非0")
    case (.some(let remaining) where remaining != 0, 0):
        print("do thing 3: ptsRemaining非0,ptsUsed为0")
    case (.some(let remaining) where remaining != 0, let used where used != 0):
        print("do thing 4: 两者都非0")
    case (.none, _):
        print("ptsRemaining为nil,单独处理")
    default:
        print("error!")
    }
}

简化写法(提前解包可选类型)

如果你能确定ptsRemaining不会为nil,或者想先处理nil的情况再进入switch,可以先用guard解包:

func updatedButtons() {
    guard let ptsRemaining = ptsRemaining else {
        print("ptsRemaining是nil,直接返回")
        return
    }
    switch (ptsRemaining, ptsUsed) {
    case (0, 0):
        print("do thing 1")
    case (0, let used) where used != 0:
        print("do thing 2")
    case (let remaining, 0) where remaining != 0:
        print("do thing 3")
    case (let remaining, let used) where remaining != 0 && used != 0:
        print("do thing 4")
    default:
        print("error!")
    }
}

这样写就不会再出现你遇到的类型错误啦~

内容的提问来源于stack exchange,提问作者dvd.Void

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:36:53