gpt4 book ai didi

swift - 创建具有特定值/存储属性的枚举

转载 作者:行者123 更新时间:2023-11-28 06:31:37 25 4
gpt4 key购买 nike

我有一个 CompassDirection 枚举,我通常在 Java 中这样定义它:

enum CompassDirection {
N(0, 1), S(0, -1), E(1, 0), W(-1, 0), NE(1, 1), NW(-1, 1), SE(1, -1), SW(-1, -1)
...

在构造函数需要 alterXalterY 整数属性的地方,存储它们,并在 alter(Position position) 方法中使用它们,如下所示:

public Position alter(Position pos) {
return new Position(pos.x + this.alterX, pos.y + this.alterY);
}

我的目标是在 Swift 中完成类似的事情。我可以轻松地在我的 alter() 方法中添加 8 种情况的 switch 语句,但这往往会增加更多的代码和困惑。

这是我在 Swift 中尝试过的:

enum CompassDirection {
case N(0, 1), S(0, -1), E(1, 0), W(-1, 0), NE(1, 1), NW(-1, 1), SE(1, -1), SW(-1, -1)

private let xAlter : Int
private let yAlter : Int

private init(_ xAlter: Int, _ yAlter: Int) {
self.xAlter = xAlter
self.yAlter = yAlter
}

func alter(position: XYPosition) -> XYPosition {
return XYPosition(x: position.x + self.xAlter, y: position.y + self.yAlter)
}
}

但是 Swift 不支持枚举中的存储属性。

将上述 Java 枚举转换为 Swift 枚举的最可读/Swifty 解决方案是什么?

最佳答案

Swift does not support stored properties in enums

您可以创建 xAlteryAlter 计算属性。这是一个高度简化的示例(只有两个主要方向):

enum CompassDirection {
case n
case s
var alterX : Int {
switch self {
case .n: return 0
case .s: return 0
}
}
var alterY : Int {
switch self {
case .n: return 1
case .s: return -1
}
}
}

现在您可以根据需要添加引用 self.alterXself.alterY 的方法。

关于swift - 创建具有特定值/存储属性的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com