泛型'与'不完全相同。错误

时间:2014-11-05 11:39:52

标签: ios swift

所以我在Swift中使用泛型来创建类似KVO的功能,但是我收到了这个错误而我无法找出原因:

error message

这是所有代码:

struct Observable<T> {
    typealias ValueType = T
    typealias SubscriptionType = Subscription<T>

    var value: ValueType {
        didSet {
            let event = ValueChangeEvent(oldValue, value)
            self.subscriptions.notify(event)
        }
    }

    var subscriptions = Subscriptions<SubscriptionType>()

    init(_ value: ValueType) {
        self.value = value
    }
}

struct ValueChangeEvent<T> {
    typealias ValueType = T

    let oldValue: ValueType
    let newValue: ValueType

    init(_ o: ValueType, _ n: ValueType) {
        oldValue = o
        newValue = n
    }
}

class Subscription<T> {
    typealias ValueType = T
    typealias HandlerType = (oldValue: ValueType, newValue: ValueType) -> ()

    let handler: HandlerType

    init(handler: HandlerType) {
        self.handler = handler
    }

    func notify(event: ValueChangeEvent<ValueType>) {
        self.handler(oldValue: event.oldValue, newValue: event.newValue)
    }
}

struct Subscriptions<T> {
    typealias ValueType = T
    typealias SubscriptionType = Subscription<T>

    private var subscriptions = Array<SubscriptionType>()

    mutating func add(handler: SubscriptionType.HandlerType) -> SubscriptionType {
        let subscription = Subscription(handler: handler)
        self.subscriptions.append(subscription)
        return subscription
    }

    mutating func remove(subscription: SubscriptionType) {
        var index = NSNotFound
        var i = 0
        for element in self.subscriptions as [SubscriptionType] {
            if element === subscription {
                index = i
                break
            }
            i++
        }

        if index != NSNotFound {
            self.subscriptions.removeAtIndex(index)
        }
    }

    func notify(event: ValueChangeEvent<ValueType>) {
        for subscription in subscriptions {
           subscription.notify(event)
        }
    }
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

基于我看到的内容,subscriptions的{​​{1}}属性看起来不正确:

Observable<T>

应该是:

var subscriptions = Subscriptions<SubscriptionType>()

我没有深入研究逻辑,所以我不能说如果改变你的代码仍然有用 - 如果没有,那么你找出错误是一个很好的起点。