Verticon
Verticon

Reputation: 2513

Why Is the Compiler Complaining About My Transform Argument to FlatMap?

I have defined a protocol and an Array extension. The compiler is reporting an error on the invocation of flatMap in the extension's encode method: Cannot convert value of type 'T?' to closure result type '_'

public protocol Encodable {
    typealias Properties = Dictionary<String, Any>
    func encode() -> Properties
    init?(_ properties: Properties?)
}

extension Array where Element : Encodable.Properties {
    func encode<T:Encodable>(type: T.Type) -> [T] {
        return flatMap{ T($0) } // <= Compiler Error
    }
}

xcode 8.3 is using swift 3.1 (perhaps I should not have updated Xcode?)

Any ideas?

Upvotes: 1

Views: 58

Answers (1)

OOPer
OOPer

Reputation: 47886

Compiling your code in a small project, I can find another error:

<unknown>:0: error: type 'Element' constrained to non-protocol type 'Encodable.Properties'

So, the constraint Element : Encodable.Properties is invalid and Swift cannot find a suitable initializer for T($0). It is often found that Swift generates inappropriate diagnostics in case of issues related to type inference.

As far as I tested, this code compiles with Swift 3.1/Xcode 8.3:

extension Array where Element == Encodable.Properties {
    func encode<T:Encodable>(type: T.Type) -> [T] {
        return flatMap{ T($0) }
    }
}

Upvotes: 2

Related Questions