Workaround for Swift Enum with raw + case type arguments?

I would like to create SKSpriteNodes using WallType

(see code below) and only if WallType

.Corner

pass it a value Side

for its orientation. The enums have original values ​​because I need to load them as numbers from plist and generate 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 way that I can pass the SKSpriteNode value for its orientation only when its WallType

- .Corner

? At the moment I initialize it with a value for orientation every time, even when it is not necessary because it WallType

constitutes it .Straight

.

I think I could make it Side

optional, but then I would have to change a lot of other code I am using Side

. And then I still have to go to nil

.

I would like to initialize the wall like this:

let wall = Wall(ofType type: WallType)

      

Information about this orientation should be inside WallType

, but only if it is .Corner

. Is there a way to expand WallType

according to my needs?

The suggestion made in this thread doesn't really apply in my case: Can bound values ​​and raw values ​​coexist in a Swift enum?

Alternatively, if I WallType

choose to remove the original value from the enum , how could I load it, does it form a plist?

Hope this makes sense! Thanks for any suggestions!

+3


source to share


1 answer


You can do this so that you leave the Side renaming for the Int subclass, but you would like to pass that enum to Wall, so make sure it takes rawValue or index and side as an argument to create the Wall.

Something like that,



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)")
}

      

0


source







All Articles