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

Swift中如何对可选枚举类型执行正确的比较检查?

解决Swift可选枚举的比较问题

嘿,刚好碰到过类似的场景,给你几种简洁又靠谱的方法来处理可选枚举的比较:

方法1:直接用==比较(最简洁)

因为你的Location枚举没有关联值,Swift会自动为它合成Equatable协议的实现,而Optional类型也会在包裹的类型遵循Equatable时自动支持相等比较。所以你可以直接这么写:

func checkStuff(currentLocation: Location?) {
    if currentLocation == .ontop {
        // 执行你的逻辑
        print("当前位置是ontop")
    }
}

这种写法最直观,和普通非可选类型的比较几乎没区别。

方法2:用if case模式匹配

如果更习惯模式匹配的写法,你可以给枚举值加上?,或者显式匹配Optional.some:

func checkStuff(currentLocation: Location?) {
    // 写法A:简洁的模式匹配
    if case .ontop? = currentLocation {
        // 执行逻辑
    }
    
    // 写法B:显式匹配Optional的some case
    if case .some(.ontop) = currentLocation {
        // 执行逻辑
    }
}

这两种写法效果完全一样,选你看着顺眼的就行。

方法3:先解包再比较(适合需要使用解包后值的场景)

如果之后需要用到currentLocation解包后的具体值,用可选绑定+条件判断会更高效:

func checkStuff(currentLocation: Location?) {
    if let currentLoc = currentLocation, currentLoc == .ontop {
        // 这里可以直接用currentLoc做其他操作
        print("当前位置是\(currentLoc)")
    }
}

修改后的完整测试代码

enum Location { case ontop case inside case underneath }
struct Item {
    var location: Location?
    func checkStuff(currentLocation: Location?) {
        // 这里用最简洁的==写法示例
        if currentLocation == .ontop {
            print("执行DO SOME STUFF逻辑")
        }
    }
}

// 测试流程
var currentLocation: Location?
var item1 = Item(location: .ontop)
item1.checkStuff(currentLocation: currentLocation) // 不会执行逻辑,因为currentLocation是nil
currentLocation = item1.location
item1.checkStuff(currentLocation: currentLocation) // 会执行逻辑,因为currentLocation现在是.ontop
var item2 = Item(location: .inside)
item2.checkStuff(currentLocation: currentLocation) // 不会执行逻辑,因为currentLocation是.ontop

内容的提问来源于stack exchange,提问作者jingo_man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:31:56