了解Swift平面地图语法

5 syntax ios swift

下面函数'parseB'中用于flatMap的语法使用括号,而不是大括号。

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 }
        self.id = 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)
}
Run Code Online (Sandbox Code Playgroud)

有一个平面地图实现看起来像这样

public func flatMap<U>(@noescape f: (Wrapped) throws -> U!) rethrows -> U!
Run Code Online (Sandbox Code Playgroud)

读完这篇文章,我仍然不明白,在上面的示例中,Episodes上的init没有括号。

有时Swift擅长推断事物,以至于很难理解正在发生的事情。有人可以帮助我理解为什么Episodes的init方法不使用括号吗?

...flatMap (Episode.init)
Run Code Online (Sandbox Code Playgroud)

Ref1:https: //talk.objc.io/episodes/S01E01-networking Ref2:https : //github.com/objcio/S01E01-networking

Khu*_*pan 0

class Employee {
    var name: String = ""

    init(name: String) {
        self.name = name
    }
}
Run Code Online (Sandbox Code Playgroud)

实例方法是 Swift 中的柯里化函数

这是一个柯里化函数,它接受单个参数 String 并返回 Employee

let employeeFunc = Employee.init  //  (String) -> Employee
Run Code Online (Sandbox Code Playgroud)

让我们在数组类型上定义我们自己的映射函数

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

        for element in self {
            result.append(f(element))
        }
        return result
    }
}


var allEmployee = [Employee]()
let names = ["Mario", "Luigi"]
Run Code Online (Sandbox Code Playgroud)

您可以一次向柯里化函数传递一个值。这个柯里化函数只需要一个参数

let firstEmployee = employeeFunc("Superman")
Run Code Online (Sandbox Code Playgroud)

类似地,我们可以将多个名称传递给多个 Employee 来创建实例

allEmployee = names.myMap(f: employeeFunc)
Run Code Online (Sandbox Code Playgroud)

我们也可以这样映射

allEmployee = names.myMap(){ employeeFunc($0)}
Run Code Online (Sandbox Code Playgroud)

让我们打印该值

for employee in allEmployee {
    print (employee.name)
}
Run Code Online (Sandbox Code Playgroud)