Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic dictionary value type in Swift

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: <T where T: Float, T: Bool>[String: T]

This throws a compiler error that only syntactic function types can be generic. I wonder if it is possible, I just don't know the correct syntax?

like image 255
Nick Avatar asked Jul 14 '14 12:07

Nick


People also ask

What is generic type in Swift?

Swift Generics allows us to create a single function and class (or any other types) that can be used with different data types. This helps us to reuse our code.

How do you declare a generic variable in Swift?

Generics allow you to declare a variable which, on execution, may be assigned to a set of types defined by us. In Swift, an array can hold data of any type. If we need an array of integers, strings, or floats, we can create one with the Swift standard library.

How do I call a generic function in Swift?

Solution. A generic function that you might need to use explicit specialization is the one that infer its type from return type—the workaround for this by adding a parameter of type T as a way to inject type explicitly. In other words, we make it infer from method's parameters instead.

How do you check if a value is in a dictionary Swift?

Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.


Video Answer


1 Answers

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.

like image 89
Rob Napier Avatar answered Oct 01 '22 07:10

Rob Napier