Contents

brightdigit/Options

Sometimes there are situations where you want to use an Enum in an OptionSet or you want Enum backed by a RawType of Int but also have String labels as well

Versatile Options

Let's say we are using an Enum for a list of popular social media networks:

enum SocialNetwork : Int {
  case digg
  case aim
  case bebo
  case delicious
  case eworld
  case googleplus
  case itunesping
  case jaiku
  case miiverse
  case musically
  case orkut
  case posterous
  case stumbleupon
  case windowslive
  case yahoo
}

We'll be using this as a way to define a particular social handle:

struct SocialHandle {
  let name : String
  let network : SocialNetwork
}

However we also want to provide a way to have a unique set of social networks available:

struct SocialNetworkSet : Int, OptionSet {
...
}

let user : User
let networks : SocialNetworkSet = user.availableNetworks()

We can then simply use `Options()` macro to generate both these types:

@Options
enum SocialNetwork : Int {
  case digg
  case aim
  case bebo
  case delicious
  case eworld
  case googleplus
  case itunesping
  case jaiku
  case miiverse
  case musically
  case orkut
  case posterous
  case stumbleupon
  case windowslive
  case yahoo
}

Now we can use the newly create SocialNetworkSet type to store a set of values:

let networks : SocialNetworkSet
networks = [.aim, .delicious, .googleplus, .windowslive]

Multiple Value Types

With the `Options()` macro, we add the ability to encode and decode values not only from their raw value but also from a another type such as a string. This is useful for when you want to store the values in JSON format.

For instance, with a type like SocialNetwork we need need to store the value as an Integer:

5

However by adding the `Options()` macro we can also decode from a String:

"googleplus"

Creating an OptionSet

We can also have a new OptionSet type created. `Options() create a new OptionSet type with the suffix -Set. This new OptionSet` will automatically work with your enum to create a distinct set of values. Additionally it will decode and encode your values as an Array of String. This means the value:

[.aim, .delicious, .googleplus, .windowslive]

is encoded as:

["aim", "delicious", "googleplus", "windowslive"]

Further Code Documentation

Documentation Here

License

This code is distributed under the MIT license. See the LICENSE file for more info.

Package Metadata

Repository: brightdigit/Options

Stars: 21

Forks: 0

Open issues: 0

Default branch: main

Primary language: swift

License: MIT

Topics: bitflags, codable, enum, optionset, swift

README: README.md