Dictionary Type (Swift)

Similar to High-level Arrays, the Swift language also supports a high-level Dictionary type that is backed by the Swift.Dictionary<T,U> record in the Swift Base Library.

var x: [String:Int]? // this is nil (and hence needs to be optional)
var x: [String:Int] = [String:Int]() // new empty dictionary instance
var x: [String:Int] = ["Five": 5, "Ten": 10] // dictionary literal with two items

Availability and Syntax

As of right now, high-level dictionaries as language feature are only available in Swift, but we are considering to back-port the feature to Oxygene and C# in the future.

A dictionary type can be written either in the long form as Swift.Dictionary<Key,Value>, or in the short form of [Key:Value], where Key and Value would be replaced by the appropriate concrete type. For example, the code above declares a dictionary with String as key type and Int as content type.

Dictionary Literals

In Swift, a dictionary literal can be written using square brackets, with pairs of key/value separated by a colon and each pair separated by a comma. These dictionary literals will not only be assignment compatible with Swift Dictionaries, but also with the platforms' standard dictionary types, such as Systems.Collections.Generic.Dictionary<T,U> on .NET and NSDictionary on Cocoa.

In C#, dictionary literals can be written in a similar fashion, but with curly braces.

var x = { "Five": 5, "Ten": 10 } // dictionary literal with two items
var x = ["Five": 5, "Ten": 10] // dictionary literal with two items

Type Mapping