robdashnash robdashnash - 1 year ago 103
Swift Question

Understanding Swift flat map syntax

The syntax used for flatMap in function 'parseB' below uses parenthesis, rather than curly brackets.

struct Episode {
let id: String
let title: String

extension Episode {
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? String, title = dictionary["title"] as? String else { return nil } = id
self.title = title

func parseA(dictionaries: [[String: AnyObject]]) -> [Episode] {
return dictionaries.flatMap { dic in Episode.init(dictionary: dic)}

func parseB(dictionaries: [[String: AnyObject]]) -> [Episode] {
return dictionaries.flatMap (Episode.init)

There is a flat map implementation that looks like so

public func flatMap<U>(@noescape f: (Wrapped) throws -> U!) rethrows -> U!

Reading this I still can't understand how, in the above example, the init on Episodes has no parenthesis.

Sometimes Swift is so good at inferring stuff it's hard to read what is going on. Could someone help me understand why the init method for Episodes is not using parenthesis please ?

...flatMap (Episode.init)


Answer Source
class Employee {
    var name: String = ""

    init(name: String) { = name

Instance Methods are Curried Functions in Swift

This is a curried function which takes a single argument String and return an Employee

let employeeFunc = Employee.init  //  (String) -> Employee

Lets define our own map function on Array Type

extension Array {
    func myMap <U> (f: (Element) -> U) -> [U] {
        var result = [U]()

        for element in self {
        return result

var allEmployee = [Employee]()
let names = ["Mario", "Luigi"]

You can pass value to curried function one at a time. This curried function only expect one argument

let firstEmployee = employeeFunc("Superman")

Similarly we can pass multiple name to multiple Employee to create instances

allEmployee = names.myMap(f: employeeFunc)

We can map like this also

allEmployee = names.myMap(){ employeeFunc($0)}

Lets print the value

for employee in allEmployee {
    print (