为什么编译器会抱怨我的变换参数为FlatMap?
问题描述:
我已经定义了一个协议和一个数组扩展。编译器在扩展的编码方法中调用flatMap时报告错误:无法转换类型'T?'的值到闭合结果类型“_”为什么编译器会抱怨我的变换参数为FlatMap?
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
}
}
- 编译器已明显发现,在可编码协议中定义的初始化 - T($ 0)将产生一个T 1。
- flatMap有一个适当的重载应该产生一个[T]。
- 我不知道什么“封闭结果类型'_'”可能意味着什么。
的Xcode 8.3是使用SWIFT 3.1(也许我不应该Xcode更新?)
任何想法?
答
编译你的代码在一个小项目,我可以找到另一个错误:
<unknown>:0: error: type 'Element' constrained to non-protocol type 'Encodable.Properties'
因此,约束Element : Encodable.Properties
无效,斯威夫特无法找到一个合适的初始化为T($0)
。经常发现Swift在与类型推断相关的问题中会产生不适当的诊断。
据我测试,这个代码编译与夫特3.1/8.3的Xcode:
extension Array where Element == Encodable.Properties {
func encode<T:Encodable>(type: T.Type) -> [T] {
return flatMap{ T($0) }
}
}
+0
非常感谢! – Verticon
尽量只'flatMap(T.init)'。这不仅是可取的,但它也可能导致更有用的错误信息 – Alexander