0

So let's say I have a structure consisting of three elements - SPEED_OF_LIGHT, SPEED_OF_SOUND, and SPEED_OF_PERSON as shown below:

public struct Fast {
    public let speed: Double

    private init(speed: Double) {
        self.speed = speed
    }

    public static let SPEED_OF_LIGHT = Fast(speed: 300000000)
    public static let SPEED_OF_SOUND = Fast(speed: 340)
    public static let SPEED_OF_PERSON = Fast(speed: 1.5)
}

If I have a double of let's say 340, how would I iterate through all of the possibilities until I find the correct match? To show exactly what I mean, I have a working code snippet that does what I want. This is done in Java.

public enum Fast {
    SPEED_OF_LIGHT(300000000),
    SPEED_OF_SOUND(340),
    SPEED_OF_PERSON(1.5);

    private double speed;

    private Fast(double speed) {
        this.speed = speed;
    }

    public static Fast getFast(double speed) {
        for (Fast f : Fast.values()) {
            if (f.speed == speed) return f;
        }
        throw new IllegalArgumentException();
    }
}

In the above case, calling getFast(340) would return SPEED_OF_SOUND. How would I do something similarly in Swift?

Matt
  • 17
  • 3

1 Answers1

1

You might want to use an enum (Swift has them too), but there is no equivalent to the values() function you call to get the list.

You would have to add an array member to the enum with the full list -- it would be a repetition of the cases, so a little error prone.

See this answer for details on how to do it: https://stackoverflow.com/a/24137319/3937

There are tricks/hacks to try to get something like values, but it's different for each version of swift and not worth the trouble in my opinion.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192