Swift枚举与原始类型+ case参数的解决方法? [英] Workaround for Swift Enum with raw type + case arguments?
问题描述
我想使用 WallType
(请参阅下面的代码)创建SKSpriteNodes,只有当 WallType
是 .Corner
传递一个 Side
的方向。
枚举有原始值,因为我需要从plist加载它们作为数字,并可以随机创建它们。
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)
}
我收到错误:类型不能有参数的情况
有没有一个解决方法,我可以传递SKSpriteNode一个值,只有当它的 WallType
是 .Corner
?
此刻,我正在初始化它,每次都有一个定向值,即使没有必要,因为它的 WallType
是。直接
。
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
.
我想我可以使 Side
可选,但是我必须改变很多其他代码,我也在使用 Side
。
然后,我仍然需要通过 nil
。
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
.
我想初始化这样的墙:
let wall = Wall(ofType type: WallType)
关于它的方向的信息应该在 WallType
内,但只有它是 .Corner
。
有没有办法扩展 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?
此线程中提出的建议在我的情况下似乎并不适用:
可以在Swift枚举中相关联的值和原始值共存?
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?
或者,如果我决定从 WallType
枚举,我将如何从plist加载?
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!
推荐答案
你可以让它离开Side枚举到Int的子类,但你会想将此枚举传递给Wall,因此请确保将rawValue或索引和边作为创建墙的参数。
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.
这样的一个
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)")
}
这篇关于Swift枚举与原始类型+ case参数的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!