【问题标题】:Use nested decended enum cases as parent enum cases使用嵌套的下降枚举案例作为父枚举案例
【发布时间】:2018-12-14 08:50:51
【问题描述】:

在流行的棋盘游戏大富翁中,玩家有机会购买/交易不同的房产,当他们垄断某个街区时,他们可以建造房屋。我试图将所有这些属性表示为 Swift 中的嵌套枚举,但是当谈到在数组中表示玩家的属性时,我感到很困惑。

这是我迄今为止尝试过的。

enum Property {
    enum Brown {
        case mediterranean, baltic
    }

    enum LightBlue {
        case oriental, vermont, connecticuit
    }

    enum pink {
        case stCharles, states, virginia
    }
    ...
}

var properties: [Property] = [
    Property.Brown.baltic, // ERROR: Cannot convert value of type 'Property.Brown' to expected element type 'Property'
    Property.Brown.mediterranean
]

如您所见,我无法将这些属性存储在 [Property] 数组中,因为 Property.Brown 不是属性(可以理解)。我需要更改什么才能将Property.<Insert Neighborhood Here>s 存储在数组中?我知道 [Any] 会起作用,但我担心类型安全,所以这不起作用。

编辑 2018 年 7 月 5 日,太平洋夏令时间 13:18 我正在编写一个程序,它将充当大富翁游戏的银行,并且需要一种方法来确定哪些玩家(或银行)拥有财产。我目前正在 Playgrounding 和原型设计,以找出适合我的方法。

【问题讨论】:

    标签: arrays swift types enums type-conversion


    【解决方案1】:

    如你所知,

    因为 Property.Brown 不是属性(可以理解)。

    您可能需要Property.BrownProperty. LightBlue、...的通用类型

    也许您可以使用仅将它们存储在数组中的协议:

    protocol PropertyEnums {}
    
    enum Property {
        enum Brown: PropertyEnums {
            case mediterranean, baltic
        }
    
        enum LightBlue: PropertyEnums {
            case oriental, vermont, connecticuit
        }
    
        //...
    }
    
    var properties: [PropertyEnums] = [
        Property.Brown.baltic,
        Property.Brown.mediterranean,
        //...
    ]
    

    但我不确定这是否是最适合您的解决方案,因为您没有展示 properties 的用例。


    对于某些用例来说,这样的事情可能会更好:

    enum Property {
        enum Brown {
            case mediterranean, baltic
        }
    
        enum LightBlue {
            case oriental, vermont, connecticuit
        }
    
        //...
    
        case brown(Brown)
        case lightBlue(LightBlue)
        //...
    }
    
    var properties: [Property] = [
        .brown(.baltic),
        .brown(.mediterranean),
        //...
    ]
    

    请告诉我们你想如何使用你的properties

    【讨论】:

    • 已编辑问题
    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    相关资源
    最近更新 更多