What do square brackets mean in parameter lists ? [ ]

(Christoph K) #1

Consider the following piece of code from AppDelegate.swift:

func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: 
[UIApplication.LaunchOptionsKey: Any]?) -> Bool 

Just trying to understand and learn the language.

(Erik Little) #2

It's not so much the [] as [:] in this case. This is just one form of declaring a dictionary type.

let dict: [String: Int] = ["Hello": 2]
let dict2: Dictionary<String, Int> = dict

(Christoph K) #3

Ah, thanks. I see. Swift has a slight resemblance with Python what the array, dictionary and tuple syntax is concerned.
On the other hand there is the square bracket nomenclature of Objective-C it could be intermixed with.

Anyway, it's got the syntax of its own. :slight_smile:

(Erik Little) #4

As an aside, although it's probably a bit much for a newcomer, Swift actually lets you make your own types become expressible by the different literals.

For example:

struct MyCustomType: ExpressibleByDictionaryLiteral {
  init(dictionaryLiteral elements: (String, Int)...) {


func doesSomething(_ x: MyCustomType) { }

doesSomething(["hello": 1])

Just something to be aware of if you ever see a literal being passed to something that doesn't take the normal literal type.

(Marcus Rossel) #5

[SomeType] is syntactic sugar for the type Array<SomeType>.
[TypeA: TypeB] is syntactic sugar for the type Dictionary<TypeA, TypeB>.