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

Swift中如何创建带关联值且某case可参数化的枚举?

问题描述

我想在Swift中创建一个带关联值的枚举,具体逻辑如下:

  • case good 返回字符串good;
  • case bad 返回字符串bad;
  • case other:无传入参数时关联默认值unknown,传入参数则使用该参数。

我尝试了两段代码:

  1. Part 1代码报错:error: enum with raw type cannot have cases with arguments
  2. Part 2代码可行,但不想通过.string属性获取值,想问有没有更简洁的写法。

附尝试代码:

// Part 1
public enum Status: String {
    case good
    case bad
    case other(s: String? = "unknown")
}
let good = Status.good // good
let bad = Status.bad //bad
let unknown = Status.other() //unknown
let knownA = Status.other(s: "up") // up
let knownB = Status.other(s: "down") // down

// Part 2
enum StatusA {
 case other(String = "unknown")
 case good, bad

 var string: String {
   switch self {
   case .good:
     return "good"
   case .bad:
     return "bad"
   case .other(let s):
     return s
   }
 }
}

let good = StatusA.good // good
let bad = StatusA.bad //bad
let unknown = StatusA.other() //unknown
let knownA = StatusA.other("up") // up
let knownB = StatusA.other("down") // down

// 输出不是预期结果
print("\(good)") // good
print("\(bad)") // bad
print("\(unknown)") // other("unknown")
print("\(knownA)") // other("up")
print("\(knownB)") // other("down")

// 输出符合预期,但不想用.string属性
print("\(good.string)") // good
print("\(bad.string)") // bad
print("\(unknown.string)") // unknown
print("\(knownA.string)") // up
print("\(knownB.string)") // down

解决方案

问题原因

Part 1报错是因为Swift的规则:带原始类型(Raw Type)的枚举,所有case都不能包含关联值,你同时使用了String原始类型和带关联值的other case,因此触发错误。

优化写法

通过实现CustomStringConvertible协议,让枚举实例直接输出目标字符串,无需额外属性调用:

enum Status: CustomStringConvertible {
    case good, bad
    case other(String = "unknown")
    
    var description: String {
        switch self {
        case .good:
            return "good"
        case .bad:
            return "bad"
        case .other(let value):
            return value
        }
    }
}

// 测试
let good = Status.good
let bad = Status.bad
let unknown = Status.other()
let knownA = Status.other("up")
let knownB = Status.other("down")

print(good)      // 输出: good
print(bad)       // 输出: bad
print(unknown)   // 输出: unknown
print(knownA)    // 输出: up
print(knownB)    // 输出: down

说明

  • CustomStringConvertible是Swift标准库协议,实现它的description属性后,直接打印枚举实例时会自动使用该属性的返回值
  • other case保留了默认参数,无传入值时自动关联unknown
  • 无需额外调用.string或其他属性,直接输出实例就能得到预期字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:45:17