具有相同案例名称的枚举以及具有不同类型的关联值 [英] Enum with identical cases names with associated values of different types

查看:103
本文介绍了具有相同案例名称的枚举以及具有不同类型的关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Swift代码进行编译:

The following Swift code compiles:

enum GraphDataSource  {
    case array(data: [Double], start: Double?, step: Double?)
    case pairs(XYValues: [Double: Double])
    case pairs(dateValues: [Date: Double])
    case function((Double) -> Double?)

    func localizedName() -> String {
        // TODO: Create localizable strings
        return NSLocalizedString(Mirror(reflecting: self).children.first?.label ?? "", comment: "")
    }
}

它有两个名为 pairs
但是,当我尝试提取关联值时,事实证明我无法选择想要的值。

It has two enum cases named pairs. But when I try to extract associated value, it turns out that I can't choose the one I want.

    var graphData = GraphDataSource.function(sin)

    switch graphData {
    case .pairs(dateValues: let vals):
        vals.keys.forEach({print($0)})
    case .pairs(XYValues: let xy): // without this case everyting compiles OK
        xy.keys.forEach({print($0)})
    default:
        break
    }

错误为:元组模式元素标签'XYValues'必须为'dateValues'。
这正常吗?像编译器这样的感觉应该要么禁止使用相同名称的情况,要么允许两者都打开。

The error is: "Tuple pattern element label 'XYValues' must be 'dateValues'". Is this normal? Feels like compiler should either disallow cases of the same name or allow to switch on both.

推荐答案

这是一个Swift编译器错误。参见 SR-10077

This is a Swift compiler bug. See SR-10077.

这篇关于具有相同案例名称的枚举以及具有不同类型的关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆