Generic dictionary value type in Swift

Solutions Collect From Internet About “Generic dictionary value type in Swift”

The tool you want for this is an enum with associated data.

enum Stuff {
  case FloatyThing(Float)
  case BoolyThing(Bool)
}

let objects = ["yes!"   : Stuff.BoolyThing(true),
               "number" : Stuff.FloatyThing(1.0)]

This captures “an object that is either a float or a bool” and provides better documentation and type safety.

To unload the data, you use a switch statement:

if let something = objects["yes!"] {
  switch something {
    case .FloatyThing(let f): println("I'm a float!", f)
    case .BoolyThing(let b): println("Am I true?", b)
  }
}

The use of the switch statement makes sure you cover all the possible types and prevents you from accidentally unloading the data as the wrong type. Pretty nice that the compiler can help you so much.

For more, see “Enumerations and Structures” in the Swift Programming Language.

I also recommend Error Handling in Swift by Alexandros Salazar for a very nice example of how this can be used to deal with common problems.