flatMap and `Ambiguous reference to member` error

断了今生、忘了曾经 提交于 2019-12-24 10:24:12

问题


Consider the following code:

typealias PersonRecord = [String : AnyObject]

struct Person {
    let name: String
    let age: Int

    public init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

extension Person {
    init?(record : PersonRecord) {
        guard let name = record["name"] as? String,
        let age = record["age"] as? Int else {
            return nil
        }

        self.name = name
        self.age = age
    }
}

Now I want to create an array of Persons from an array of Records:

let records = // load file from bundle
let persons = records.flatMap(Person.init)

But I get the following error:

error: ambiguous reference to member 'init(name:age:)'

If I move the failable initializer out of the extension, I still get the same error.

What am I missing here, is this not a correct usage of flatMap?

EDIT - solved:

Found the error: the code that read in the records file from disk, returned the wrong type. Once I fixed that, the error went away.


回答1:


For this to work

let persons = records.flatMap(Person.init)

the param passed to the flatMap closure must be the same type received by Person.init, so it must be PersonRecord.

Then records must be a list of PersonRecord, something like this

let records: [PersonRecord] = []

Now it works

let persons = records.flatMap(Person.init)    



回答2:


Most of the times the Ambiguous reference to member in a map or flatMap is because the return type isn't specified

array.flatMap({ (item) -> ObjectToReturn? in })


来源:https://stackoverflow.com/questions/40196077/flatmap-and-ambiguous-reference-to-member-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!