So, I’ve been looking for a solution to this problem for about 2 days. I’ve rummaged the Swift documentation, tried many different google / stack overflow searches, and just straight up randomly wrote code to no avail. I think part of the problem is that I don’t know how to word it... so sorry is this is confusing, but hopefully the code I attached clears it up.
Anyways, I want to know if it’s possible to have a private field in an enum such that each enum value has its own value for this field. I am not asking about extending another class, and I’m not asking about associated values. Unfortunately, I have yet to come across anything online saying whether this is allowed in Swift, and so, how to do it. To highlight my question, I’m trying to recreate the following Java code in Swift:
// Java
public enum Direction {
LEFT(0, -1), RIGHT(0, 1), UP(-1, 0), DOWN(1, 0);
private final int rowChange, colChange;
Direction(int rowChange, int colChange) {
this.rowChange = rowChange;
this.colChange = colChange;
}
public int rowChange() {
return this.rowChange;
}
public int colChange() {
return this.colChange;
}
}
This is what I have at the moment, which works, but I would rather have it have stored values rather than switching through each possible case.
// Swift
public enum Direction {
case left, right, up, down
public func rowChange() -> Int {
switch self {
case .left:
return 0
case .right:
return 0
case .up:
return -1
case .down:
return 1
}
}
public func colChange() -> Int {
switch self {
case .left:
return -1
case .right:
return 1
case .up:
return 0
case .down:
return 0
}
}
}