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

Swift:如何合并枚举中多个String类型的集合?

解决方法

你的代码问题出在使用了joined()方法,joined()仅适用于元素本身是序列类型(比如数组、集合)的集合,而Test.all的元素是Test枚举实例,并没有这个方法,所以会编译报错。

要实现合并所有枚举case的chars集合元素的需求,只需要用flatMap展开每个枚举实例的chars集合,再将结果转换为Set即可:

enum Test {
    static let all: [Test] = [.a, .b, .c]
   
    case a, b, c

    var chars: Set<String> {
        switch self {
            case .a: 
                return ["a", "b", "c"]
            case .b: 
                return ["d", "e", "f"]
            case .c: 
                return ["g", "h", "i"]
        }
    }
    
    static var allCharacters: Set<String> {
        return Set(Test.all.flatMap { $0.chars })
    }
}

或者你也可以用reduce的方式逐步合并集合,逻辑更直观:

static var allCharacters: Set<String> {
    return Test.all.reduce(into: Set<String>()) { result, testCase in
        result.formUnion(testCase.chars)
    }
}

两种方式都能得到包含所有chars元素的集合,如果你需要最终结果是数组类型,只需要把返回类型改成[String],并将结果用Array()包裹即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:15:34