gpt4 book ai didi

ios - 泛型 'is not identical to' 错误

转载 作者:行者123 更新时间:2023-11-28 07:14:48 25 4
gpt4 key购买 nike

所以我正在尝试在 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)
}
}
}

如有任何帮助,我们将不胜感激。

最佳答案

根据我所看到的,它看起来像 subscriptions Observable<T>的属性(property)定义不正确:

var subscriptions = Subscriptions<SubscriptionType>()

而它应该是:

var subscriptions = Subscriptions<ValueType>()

我没有深入研究逻辑,所以我不能说经过这些更改后您的代码是否仍然有效 - 如果不能,这是您找出问题所在的一个很好的起点。

关于ios - 泛型 'is not identical to' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26756347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com