How do you pass multiple enum values in C#?
When you define the enum, just attribute it with [Flags], set values to powers of two, and it will work this way.
Nothing else changes, other than passing multiple values into a function.
For example:
[Flags]
enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public void RunOnDays(DaysOfWeek days)
{
bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;
if (isTuesdaySet)
//...
// Do your work here..
}
public void CallMethodWithTuesdayAndThursday()
{
this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}
For more details, see MSDN's documentation on Enumeration Types.
Edit in response to additions to question.
You won't be able to use that enum as is, unless you wanted to do something like pass it as an array/collection/params array. That would let you pass multiple values. The flags syntax requires the Enum to be specified as flags (or to bastardize the language in a way that's its not designed).
How to pass multiple enum values as a function parameter
Edit: In Swift 3.0:
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
Edit: This is how you would use the options enum in Swift 2.0:
let options: NSStringDrawingOptions = [.UsesLineFragmentOrigin, .UsesFontLeading]
Edit: The issue has been resolved in iOS 8.3 SDK Beta 1 (12F5027d):
Modified
NSStringDrawingOptions
[struct]
- From:
enum NSStringDrawingOptions : Int
- To:
struct NSStringDrawingOptions : RawOptionSetType
You can now write:
let options : NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading
After some research and and @Anton Tcholakov's "comment":
If you're targeting OS X 10.10, this is as simple way to do it:
let size = CGSize(width: 280, height: Int.max)
let options : NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading
let boundingRect = string.bridgeToObjectiveC().boundingRectWithSize(size, options: options, attributes: attributes, context: nil)However, in iOS 8 SDK (in the current seed), there's a bug, where
NSStringDrawingOptions
is ported to Swift asenum : Int
, instead ofstruct : RawOptionSet
. You should send a bug report to Apple describing this serious problem.
Pass multiple enum to methods and get their values
Here are few steps to follow to get flagged enum :
- Use
2 exp (n)
integer (1, 2, 4, 8, 16, 32, ...)
to define your enum. Why ? : Actually each active state of your
enum will take a single bit of a 32 bits integer. - Add the Flags attribute.
Then,
[Flags]
public enum Status
{
S1 = 1,
S2 = 2,
S3 = 4,
S4 = 8
}
You can use Enum.HasFlag to check if a specific status is active :
public void DoWork(Status s)
{
var statusResult = Enum.GetValues(typeof(Status)).Where(v => s.HasFlag(v)).ToArray() ;
// StatusResult should now contains {1, 2}
}
C++ Multiple enum elements being passed as parameter?
That is just a bitwise OR
, which allows to combine more than one enum value into the integer which is is, internally (so still just one argument in the function call). Such enums are also called a flagset. They are usually characterized by members that have values which represent just one bit: a = 1, b = 2, c = 4, d = 8, e = 16, ... so they can be combined; a | b
is 3 when casted to int.
Inside the function body, individual flags are then queried separately using the bitwise &
operator.
additional reference: How to use enums as flags in C++?
btw. this concept seems to be quite similar in Java: Implementing a bitfield using java enums
How to pass multiple enum types as method arguments and then call common methods on them?
Try using:
e.getClass().getEnumConstants()
How to pass multiple enum values to a variable in ReactJs typescript
Given the enum values are string, a simple array would suffice i.e. config.disallowedColors = [COLOR.RED, COLOR.YELLOW]
.
When checking, you can leverage includes
/ some
etc. to check if a flag is set e.g.
config.disallowedColors.includes(COLOR.RED);
It gets slightly more complicated when you need to check for multiple values, one option would be to create a temp array for the values you want to check are present, and then leverage every
comparing each one to the target array i.e.
const flags = [COLOR.RED, COLOR.YELLOW];
const { disallowedColors } = config;
flags.every(c => disallowedColors.includes(c));
Alternatively, if you used a numerical value then you could leverage Bitwise Operations to create a bit mask which would give you the same result (just in a different way) i.e.
// values should be ^2
enum COLOR {
NONE = 0
RED = 1,
BLUE = 2,
YELLOW = 4,
...
}
...
// setting multiple flags
const colors = COLOR.RED | COLOR.YELLOW;
// check for existence of single flag
const isRed = (colors & COLOR.RED) === COLOR.RED;
// check for existence of multiple flags
const flags = COLOR.RED | COLOR.YELLOW;
const hasMultiple = (colors & flags) === flags;
c++ multiple enums in one function argument using bitwise or |
For that you have to make enums like :
enum STATE {
STATE_A = 1,
STATE_B = 2,
STATE_C = 4
};
i.e. enum element value should be in power of 2 to select valid case or if statement.
So when you do like:
void foo( int state) {
if ( state & STATE_A ) {
// do something
}
if ( state & STATE_B ) {
// do something
}
if ( state & STATE_C ) {
// do something
}
}
int main() {
foo( STATE_A | STATE_B | STATE_C);
}
How to input multiple parameters into an enum constructor?
I have rewritten your class and enum. You should do it this way.
And your understanding of the enum is incorrect. As you can think enum of named constants. You can't put data variables and functions inside the enum.
enum Suit {
Hearts,
Spades,
Clubs,
Diamond
}
enum Rank {
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
Jack,
Queen,
King,
Ace
}
class CardMaker {
Suit name;
Rank rank;
public CardMaker(final String cardName, final String cardRank) {
this.name = Suit.valueOf(cardName);
this.rank = Rank.valueOf(cardRank);
}
@Override
public String toString() {
return "Name : " + name + " rank : " + rank;
}
}
class Scratch {
public static void main(String[] args) {
CardMaker card = new CardMaker(Suit.Hearts.name(), Rank.ONE.name());
System.out.println(card);
}
}
Related Topics
Swift - Spritekit Cgpoint Alignment
What Is Geometry Reader in Swiftui
Getting "File Not Found" in Bridging Header When Importing Objective-C Frameworks into Swift Project
Can You Execute an Applescript Script from a Swift Application
Swift Variable Name With ' (Backtick)
Deletable Table With Textfield on Swiftui
Delete Folder With Contents from Firebase Storage
How to Use Assets Catalog Color Sets
How to Get Monday'S Date of the Current Week in Swift
Swift Function Object Wrapper in Apple/Swift
Sharing Userdefaults Between Extensions
Swift Compiler Segmentation Fault When Building
How to Do a Swift For-In Loop With a Step
Using 'Self' in Class Extension Functions in Swift
What Is the Cause of This Type Error
Alamofire Get API Request Not Working as Expected