Duck
Duck

Reputation: 35933

What is this swift declaration doing?

According to the author of this page this is declaring a dictionary of dictionaries in swift:

var routeMap : Dictionary<String, Dictionary<String, () -> ()>> = [:]

can you explain what are this doing, specially the part with these hieroglyphs () -> ()>> = [:] at the end?

It appears that the guy is joining a series of commands together. If this is the case, if you can unfold that code into several lines I appreciate.

thanks.

Upvotes: 2

Views: 239

Answers (1)

Ryan
Ryan

Reputation: 3993

Let's start at the way end.

[:]

This is simply initializing an empty Dictionary. It is very similar to calling "" to initialize an empty String, or [] to initialize an empty Array.

Now, let's jump to the type declaration.

Dictionary<String, Dictionary<String, () -> ()>>

This is a dictionary that maps Strings to Dictionaries. Let's look closer at the type of those inner dictionaries.

Dictionary<String, () -> ()>

This maps a String to a closure. A closure is pretty much just a block from Objective C. That's what the () -> () means. Let's dive deeper.

() -> ()

This is the syntax for declaring a closure. The left value are the parameters. The right are the return types. In this case, we have one parameter, and one return type.

()

This means void in Swift. In fact, in Swift.h, we can see this on line 3953:

typealias Void = ()

So ultimately, we have a closure that gives no (void) parameters, and has no (void) return value.

Some more examples of closures might help understand the syntax. Let's imagine a closure that takes a String and converts it to an int. The type would look like this:

let stringToInt: (String) -> (Int) = ...

Now, one with a void input. Let's have a random number generator:

let randomDouble: () -> (Double) = ...

This takes no inputs, and returns a Double.

Finally, let's have a void to void.

let printHelloWorld: () -> () = ...

You can see this takes no arguments and returns nothing. It's more of a method than a function, but it can still do stuff, like modify properties, or in this case, print to the console.

Upvotes: 12

Related Questions