Generic dictionary value type in Swift

后端 未结 1 764
一整个雨季
一整个雨季 2020-12-06 20:09

I\'m trying to create a dictionary variable whose values are one of two types. An example of my attempt should make this clearer:

var objects: 

        
相关标签:
1条回答
  • 2020-12-06 20:12

    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.

    0 讨论(0)
提交回复
热议问题