以下是编译器错误还是我做错了什么:
protocol Subscriptable {
associatedtype Element
associatedtype Index
var firstIndex: Index { get }
var lastIndex: Index { get }
subscript(index: Index) -> Element { get set }
}
struct AnySubscriptable<E, I>: Subscriptable {
typealias Element = E
typealias Index = I
let firstIndexee: () -> I
let lastIndexee: () -> I
let subscriptee: (index: I) -> E
let setSubscriptee: (index: I, element: E) -> Void
var firstIndex: I { return firstIndexee() }
var lastIndex: I { return lastIndexee() }
subscript(index: I) -> E {
get { return subscriptee(index: index) }
set { setSubscriptee(index: index, element: newValue) }
}
}
extension Array {
var asScriptable: AnySubscriptable<Element, Int> {
return AnySubscriptable(
firstIndexee: { return self.startIndex }, // Error: Cannot convert `() -> Int` to expected `() -> _`
lastIndexee: { return self.endIndex },
subscriptee: { return self[$0] },
setSubscriptee: { self[$0] = $1 }
)
}
}
错误,&#34;无法将() -> Int
转换为预期() -> _
&#34;,在firstIndexee
关闭扩展程序中是奇怪的,因为:
lastIndexee
set
中的subscript
被Subscriptable
移除,setSubscriptee
等AnySubscriptable
和{{1}}中的{{1}}移除,则错误就会消失。 编译错误或我的错误?
提前感谢您的帮助,
- 霍华德。
答案 0 :(得分:0)
该错误消息具有误导性,self
捕捉setSubscriptee
self
的{{1}}可变副本所需要的内容:
extension Array {
var asSubscriptable: AnySubscriptable<Element, Int> {
var mutableSelf = self // Without this line type inference fails with a *very* misleading error message!
return AnySubscriptable(
firstIndexee: { return self.startIndex },
lastIndexee: { return self.endIndex },
subscriptee: { return self[$0] },
setSubscriptee: { mutableSelf[$0] = $1 }
)
}
}