In Swift can I use a tuple as the key in a dictionary?

swift tuple
swift dictionary
set of tuples swift
swift tuple list
swift add to dictionary
swift tuple parameter
swift return tuple
swift dictionary to array of tuples

I'm wondering if I can somehow use an x, y pair as the key to my dictionary

let activeSquares = Dictionary <(x: Int, y: Int), SKShapeNode>()

But I get the error:

Cannot convert the expression's type '<<error type>>' to type '$T1'

and the error:

Type '(x: Int, y: Int)?' does not conform to protocol 'Hashable'

So.. how can we make it conform?


The definition for Dictionary is struct Dictionary<KeyType : Hashable, ValueType> : ..., i.e. the type of the key must conform to the protocol Hashable. But the language guide tells us that protocols can be adopted by classes, structs and enums, i.e. not by tuples. Therefore, tuples cannot be used as Dictionary keys.

A workaround would be defining a hashable struct type containing two Ints (or whatever you want to put in your tuple).

How do I make (Int,Int) Hashable? |Apple Developer Forums, Hence it cannot be used as dictionary keys. Creating a tuple: You can declare a tuple like any other variable or constant. To initialize it you will  You can declare a tuple like any other variable or constant. To initialize it you will need a another tuple or a tuple literal. A tuple literal is a list of values separated by commas between a


As mentioned in the answer above, it is not possible. But you can wrap tuple into generic structure with Hashable protocol as a workaround:

struct Two<T:Hashable,U:Hashable> : Hashable {
  let values : (T, U)

  var hashValue : Int {
      get {
          let (a,b) = values
          return a.hashValue &* 31 &+ b.hashValue
      }
  }
}

// comparison function for conforming to Equatable protocol
func ==<T:Hashable,U:Hashable>(lhs: Two<T,U>, rhs: Two<T,U>) -> Bool {
  return lhs.values == rhs.values
}

// usage:
let pair = Two(values:("C","D"))
var pairMap = Dictionary<Two<String,String>,String>()
pairMap[pair] = "A"

Tuple in Swift - Abhimuralidharan, The values in a tuple can be of any type and the same tuple can contain differently from dictionaries they cannot be used as Dictionary keys). Yes, I just did a timing test and although Tuples can be used successfully, creating your own class that implements IEqualityComparer<T> and uses the XOR'ed GetHashCode() of the components, and the logically AND'ed Equals() of the components (for GetHashCode() and Equals() respectively) performs significantly better than using a plain Tuple.


I created this code in an app:

struct Point2D: Hashable{
    var x : CGFloat = 0.0
    var y : CGFloat = 0.0

    var hashValue: Int {
        return "(\(x),\(y))".hashValue
    }

    static func == (lhs: Point2D, rhs: Point2D) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y
    }
}

struct Point3D: Hashable{
    var x : CGFloat = 0.0
    var y : CGFloat = 0.0
    var z : CGFloat = 0.0

    var hashValue: Int {
        return "(\(x),\(y),\(z))".hashValue
    }

    static func == (lhs: Point3D, rhs: Point3D) -> Bool {
        return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
    }

}

var map : [Point2D : Point3D] = [:]
map.updateValue(Point3D(x: 10.0, y: 20.0,z:0), forKey: Point2D(x: 10.0, 
y: 20.0))
let p = map[Point2D(x: 10.0, y: 20.0)]!

Swift Tuple - If let swift = Programming!, In this article we take an in-depth look at how to use Tuples in Swift. I could iterate over the dictionary using a for-in loop and each key/value pair in the  Tuples are one of Swift's less visible language features. They occupy a small space between Structs and Arrays. In addition, there's no comparable construct in Objective-C (or many other languages). Finally, the usage of tuples in the standard library and in Apple's example code is sparse. One could get the impression that their raison d'être in Swift is pattern matching, but we disgress.


If you don't mind a bit of inefficiency, you can easily convert your tuple to a string and then use that for the dictionary key...

var dict = Dictionary<String, SKShapeNode>() 

let tup = (3,4)
let key:String = "\(tup)"
dict[key] = ...

Tuples in Swift, Another key difference is the type of values an array can store. Swift aims to be intuitive and easy to use, and its implementation of mutability is a Similar to arrays and dictionaries, tuples can contain values of any type. Swift 4 dictionaries use unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers.


Unfortunately, as of Swift 4.2 the standard library still doesn't provide conditional conformance to Hashable for tuples and this is not considered valid code by the compiler:

extension (T1, T2): Hashable where T1: Hashable, T2: Hashable {
  // potential generic `Hashable` implementation here..
}

In addition, structs, classes and enums having tuples as their fields won't get Hashable automatically synthesized.

While other answers suggested using arrays instead of tuples, this would cause inefficiencies. A tuple is a very simple structure that can be easily optimized due to the fact that the number and types of elements is known at compile-time. An Array instance almost always preallocates more contiguous memory to accommodate for potential elements to be added. Besides, using Array type forces you to either make item types the same or to use type erasure. That is, if you don't care about inefficiency (Int, Int) could be stored in [Int], but (String, Int) would need something like [Any].

The workaround that I found relies on the fact that Hashable does synthesize automatically for fields stored separately, so this code works even without manually adding Hashable and Equatable implementations like in Marek Gregor's answer:

struct Pair<T: Hashable, U: Hashable>: Hashable {
  let first: T
  let second: U
}

Swift From Scratch: Collections and Tuples, Swift tuples are a compound value container that can include multiple When you access the element, you can just use dot followed by the name is that tuples cannot be keys in a dictionary or elements in a set, as keys for  Create a new dictionary by using a dictionary literal. A dictionary literal is a comma-separated list of key-value pairs, in which a colon separates each key from its associated value, surrounded by square brackets. You can assign a dictionary literal to a variable or constant or pass it to a function that expects a dictionary.


Understand the Pros and Cons of Tuples in Swift, Swift provides three primary collection types, known as arrays, sets, and the enumerated() method returns a tuple composed of an integer and the item. You can use your own custom types as set value types or dictionary key types by  Swift Programming from Scratch The Swift Sandbox is integrated, making the exercises interactive. Read more about the book here. First Steps Conditionals Types Loops Strings Arrays Functions Recursion Closures Tuples & Enums Dictionaries Chapter 11: Dictionaries A dictionary is an unordered collection that stores multiple values of the same type.


Collection Types, With this update to Swift, you can use the Dictionary(grouping:by) Using .​bakery as a key in groceriesByDepartment gives you the array [🥐, ] . Each element of zippedNames is a (String, GroceryItem) tuple, the first of  A dictionary can be passed as an argument to a func. We specify the type of the keys and the values. In Swift we use a ":" to begin a type description. Here: We pass the stocks dictionary of String keys and Double values to a validate func. A guard statement ensures the dictionary has data.


Dictionary and Set Improvements in Swift 4.0, In this example an array of tuples is created to simulate key/value will ultimately be used to create a new dictionary of even key / value pairs. To print all the keys of a dictionary, we will iterate through each (key, value) pair of the dictionary and then access the key alone. Example – Get all keys in a Swift Dictionary In this example, we will create a Swift Dictionary with some initial values and print all the keys of the Dictionary.