for associative arrays we can write
if( elem in array) { .. }
what do we write for a simple array? I want to write validation e.g.
enforce(input in [10,20,40]);
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
in
sadly doesn't work on array. You must use canFind
or search
defined in std.algorithm
http://dlang.org/phobos/std_algorithm.html. Since you only want to know if it's present, not where it is, canFind
is the right tool.
import std.algorithm: canFind;
if (my_array.canFind(42)) { stuff }
In addition to canFind, there is also countUntil which will get you the index of the first occurrence.
Note that D's "in" keyword searches the associative array's keys and not its values :
string[string] array = [
"foo" : "bar"
];
writeln(("foo" in array) != null); // true
writeln(("bar" in array) != null); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With