简体   繁体   中英

Function with Enumeration Parameter (and Default value)

I wanted to create an extension method function called toCurrencyString that has one parameter that is actually an integer enumeration of type CurrencyFormatType. The enum and code would be:

enum CurrencyFormatType: Int {
    /// Formats a standard currency string (localized) such as $45.35 or *45,00
    case Standard = 1,

    ///Rounded currency format (rounds up last decimals and does not return any decimals in string)
    Rounded,

    ///Will not include the thousands separator (, or .) in a string. Retains localized currency symbol.
    WithoutThousandsSeparator

}


func toCurrencyString(currencyFormat: CurrencyFormatType = 1) -> String
{
  ..my switch code w/ default to the first option if nothing passed in
}

I'd like to do this so that I can call .toCurrencyString on NSDecimalNumbers without having to pass in the optional parameter (most of the time I won't need it), but on the few times I do, i'd like to use an enum to select other options.

It complains at me telling me that my enum doesn't conform to IntegerLiteralConvertible. I did a little reading on how this would work but couldn't figure out the code.

Could anyone shed some light on how to get this working?

thanks for your help!

My apologies, no sooner did I ask it than I figured it out. I should have waited a bit longer. In hopes of helping others out, just a reminder about the 'Raw' aspect of enums:

Adding this to my function signature helped:

CurrencyFormatType.Raw = 1

Thanks!

alternately you could have done:

func toCurrencyString(currencyFormat: CurrencyFormatType = CurrencyFormatType.Standard) -> String
{
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM