'access var from enum inside a class
I've following code but unable to access app from Enum
open class Foo {
private var app: Bar
enum Directions: String {
case north = "NorthId"
case south = "SouthId"
case east = "EastId"
case west = "WestId"
case northEast = "NorthEastId"
case northWest = "NorthWestId"
case southEast = "SouthEastId"
case southWest = "SouthWestId"
var dir: String {
switch self {
case .north, .south, .east, .west
return app.getDirection[self.rawValue]
case northEast, northWest, southEast, southWest
return app.getCoordinates[self.rawValue]
}
}
}
}
Here issue is app is not accessible inside enum Directions. How can I access class variable app inside the another class variable Enum Directions.
Thank you for your help
Solution 1:[1]
How can I access class variable app inside the another class variable Enum Directions.
There's a mistake in this question. app
isn't a class variable. It's an instance variable that belongs to instances of the class Foo
. That is, there's one value app
per object of Foo
.
This then begs the question, if the Directions
enum was trying to access an app
value, which one should it use?
Put another way, a name is an instance variables of humans. It makes sense to ask "What is the name of this person?". However, it doesn't make sense to ask "What is the name of Person?"... well... which person? Yet, this is exactly what you're trying to do in Directions
enum.
It's hard recommend a solution without more context about what you're trying to achieve, but I can confidently say that it would be incorrect for the Directions
enum (which is just a simple little type that describes 8 cardinal directions) to do anything at all involving an "app", or any other such high-level concepts.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alexander |