在可设置的下标上键入擦除会产生奇怪的错误;这是一个编译器错误还是我做错了什么?

时间:2016-03-23 23:52:56

标签: xcode swift

以下是编译器错误还是我做错了什么:

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关闭扩展程序中是奇怪的,因为:

  1. 类型正确
  2. lastIndexee
  3. 没有错误
  4. 如果set中的subscriptSubscriptable移除,setSubscripteeAnySubscriptable和{{1}}中的{{1}}移除,则错误就会消失。
  5. 编译错误或我的错误?

    提前感谢您的帮助,

    - 霍华德。

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 }
        )
    }
}