|
94 | 94 | pointsDict["Blue"] = 150; // Add "Blue" as a key and assign 150 as its value. |
95 | 95 | [/csharp] |
96 | 96 | [/codeblocks] |
97 | | - Finally, dictionaries can contain different types of keys and values in the same dictionary: |
| 97 | + Finally, untyped dictionaries can contain different types of keys and values in the same dictionary: |
98 | 98 | [codeblocks] |
99 | 99 | [gdscript] |
100 | 100 | # This is a valid dictionary. |
|
133 | 133 | } |
134 | 134 | [/csharp] |
135 | 135 | [/codeblocks] |
| 136 | + To enforce a certain type for keys and values, you can create a [i]typed dictionary[/i]. Typed dictionaries can only contain keys and values of the given types, or that inherit from the given classes: |
| 137 | + [codeblocks] |
| 138 | + [gdscript] |
| 139 | + # Creates a typed dictionary with String keys and int values. |
| 140 | + # Attempting to use any other type for keys or values will result in an error. |
| 141 | + var typed_dict: Dictionary[String, int] = { |
| 142 | + "some_key": 1, |
| 143 | + "some_other_key": 2, |
| 144 | + } |
| 145 | + |
| 146 | + # Creates a typed dictionary with String keys and values of any type. |
| 147 | + # Attempting to use any other type for keys will result in an error. |
| 148 | + var typed_dict_key_only: Dictionary[String, Variant] = { |
| 149 | + "some_key": 12.34, |
| 150 | + "some_other_key": "string", |
| 151 | + } |
| 152 | + [/gdscript] |
| 153 | + [csharp] |
| 154 | + // Creates a typed dictionary with String keys and int values. |
| 155 | + // Attempting to use any other type for keys or values will result in an error. |
| 156 | + var typedDict = new Godot.Collections.Dictionary<String, int> { |
| 157 | + {"some_key", 1}, |
| 158 | + {"some_other_key", 2}, |
| 159 | + }; |
| 160 | + |
| 161 | + // Creates a typed dictionary with String keys and values of any type. |
| 162 | + // Attempting to use any other type for keys will result in an error. |
| 163 | + var typedDictKeyOnly = new Godot.Collections.Dictionary<String, Variant> { |
| 164 | + {"some_key", 12.34}, |
| 165 | + {"some_other_key", "string"}, |
| 166 | + }; |
| 167 | + [/csharp] |
| 168 | + [/codeblocks] |
136 | 169 | [b]Note:[/b] Dictionaries are always passed by reference. To get a copy of a dictionary which can be modified independently of the original dictionary, use [method duplicate]. |
137 | 170 | [b]Note:[/b] Erasing elements while iterating over dictionaries is [b]not[/b] supported and will result in unpredictable behavior. |
138 | 171 | </description> |
|
0 commit comments