Workaround for Swift Enum with raw type + case arguments?

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

I'd like to create SKSpriteNodes with a WallType (please see code below), and only if that WallType is .Corner pass it a Side value for its orientation. The enums have raw values because I need to load them as numbers from a plist and be able to create them randomly.

enum Side: Int {   case Left = 0, Right }  enum WallType: Int {   case Straight = 0   case Corner(orientation: Side) } 

I get the error: "Enum with raw type cannot have cases with arguments"

Is there a workaround where I can pass the SKSpriteNode a value for its orientation only when its WallType is .Corner? At the moment I'm initialising it with a value for orientation every time, even when it is not necessary because its WallType is .Straight.

I guess I could make Side optional but then I would have to change a lot of other code where I'm using Side as well. And then, I'd still have to pass in nil.

I'd like to initialise the wall like that:

let wall = Wall(ofType type: WallType) 

The information about it's orientation should be inside the WallType, but only if it is .Corner. Is there a way to extend WallType to fit my needs?

The suggestion made in this thread doesn't really seem to apply in my case: Can associated values and raw values coexist in Swift enumeration?

Alternatively, if I decided to take away the raw value from the WallType enum, how would I go about loading it form a plist?

I hope that makes sense! Thanks for any suggestions!

回答1:

You can make it so that you leave the Side enum to subclass from Int but you would want to pass this enum to Wall, so make sure that it takes the rawValue or index and side as the argument for creating the Wall.

Something like this,

enum Side: Int {     case Left = 0, Right }  enum Wall {     case Straight(Int)     case Corner(Int,Side) }  let straight = Wall.Straight(0) let corner = Wall.Corner(1, .Left)  switch straight {     case .Straight(let index):         print("Value is \(index)")     case .Corner(let index, let side):         print("Index is: \(index), Side is: \(side)") } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!