如何在元组的switch语句中匹配多个枚举case?
Swift中Switch元组匹配多个Enum Case的正确方式
你之前的写法错误是因为把多个enum case包装成了元组,但enumValue本身是MyEnum类型而非元组,所以编译器无法匹配。以下是几种可行的实现方式:
方式一:合并多个case分支
直接将符合条件的元组模式用逗号分隔,这是最基础的写法,兼容所有Swift版本:
switch (enumValue, myArray.isEmpty) { case (.one, true): // 处理 .one 且数组为空的逻辑 case (.one, false), (.two, false): // 处理 .one 或 .two 且数组不为空的逻辑 default: // 处理其他所有情况 }
方式二:使用where分句过滤
如果需要匹配的enum case较多,用where分句可以让代码更简洁:
switch (enumValue, myArray.isEmpty) { case (.one, true): // 处理 .one 且数组为空的逻辑 case let (caseValue, false) where caseValue == .one || caseValue == .two: // 处理 .one/.two 且数组不为空的逻辑 default: // 处理其他所有情况 }
方式三:Swift 5.3+ 专用的OR模式匹配
Swift 5.3及以上版本支持在模式中直接用|运算符匹配多个enum case,写法更紧凑:
switch (enumValue, myArray.isEmpty) { case (.one, true): // 处理 .one 且数组为空的逻辑 case (.one | .two, false): // 处理 .one 或 .two 且数组不为空的逻辑 default: // 处理其他所有情况 }
内容的提问来源于stack exchange,提问作者meaning-matters
相关产品推荐
相关产品推荐

