I'm trying to use flatMap to build a Resource<T>
in Swift, but keep getting a strange error, and only works when I force the cast.
Resource<T>
:
public struct Resource<T> {
let record: CKRecord
let parser: [String: AnyObject] -> T?
}
Working code:
public func buildResource<T>(resource: Resource<T>) -> T? {
var dataJson: [String: AnyObject] = [:]
dataJson["recordID"] = resource.record.recordID
for name in resource.record.attributeKeys {
dataJson[name] = resource.record[name]
}
return (dataJson as? [String: AnyObject]).flatMap(resource.parser)
}
The code above gives a warning that the casts always succeeds, which is true. But when I try to remove the cast like so:
public func buildResource<T>(resource: Resource<T>) -> T? {
var dataJson: [String: AnyObject] = [:]
dataJson["recordID"] = resource.record.recordID
for name in resource.record.attributeKeys {
dataJson[name] = resource.record[name]
}
return dataJson.flatMap(resource.parser)
}
It gives the following error: 'flatMap' produces '[S.Generator.Element]', not the expected contextual result type 'T'?
.
The parser is a struct init
like so:
struct Example {
let name: String
let id: Int
}
extension Example {
init?(dataJson: [String: AnyObject]) {
guard let name = dataJson["name"] as? String else {
return nil
}
guard let id = dataJson["id"] as? Int else {
return nil
}
self.name = name
self.id = id
return
}
}
Any ideas how to fix this or a different approach? The idea here is to transform any CKRecord into a struct easily without needing to write a lot of boilerplate code.