Check if a value is in an enum

Hello,

I have an enum like

julia> @enum Fruit apple=1 orange=2 kiwi=3

I can check that apple is a Fruit

julia> apple isa Fruit
true

But can’t check if 3 is an “allowed” value (ie a value which is used by this enum)

julia> 4 isa Fruit
false

julia> 3 isa Fruit
false

I tried 3 in Fruit or 3 in keys(Fruit) but enum are not iterable.

I haven’t dive into Enum internals… but maybe someone here can help.

(and docstring could probably be improved)

Kind regards

You could use the instances function.

For example, you can define

const fruitvals = Set(Int(f) for f in instances(Fruit))

and then do

julia> 3 in fruitvals
true

julia> 17 in fruitvals
false
2 Likes

If you need something generic, the only real way I can see is the ugly

julia> function ismember(enum::Type{T}, v::Int) where T<:Enum
           try
               T(v)
               return true
           catch
               return false
           end
       end
ismember (generic function with 1 method)

julia> @enum Fruit apple=1 orange=2 kiwi=3

julia> ismember(Fruit, 1)
true

julia> ismember(Fruit, 4)
false

The list of available values (https://github.com/JuliaLang/julia/blob/29b47b8a10397324a820717af655cb0ee1d7f023/base/Enums.jl#L133) is not easily available (edit: nvm, see below).

1 Like

You can also use the undocumented internal function Base.Enums.namemap:

julia> 4 in keys(Base.Enums.namemap(Fruit))
false

and there are also the typemin and typemax functions to get the minimum and maximum allowed values:

julia> Int.((typemin(Fruit), typemax(Fruit)))
(1, 3)