我有两种协议,一种为对象分配了一个 serverId
,另一种为其分配了一个 status
(即它是否已发布到服务器)。
这两个协议允许我处理我的服务器模型和Core Data之间的同步。
/// By conforming to this protocol, classes AND struct have an identifiable serverid `Int64`
protocol RemoteObject {
var serverId: ServerId { get set }
}
/// This can only be applied to class
protocol Syncable: class {
var syncStatus: SyncStatus { get set }
}
enum SyncStatus: Int64 {
case published
case local
}
它背后的思想是,可以将
RemoteObject
应用于结构体(即从服务器获取的JSON结构)和类(NSManagedObject
)。而Syncable
只能应用于类(NSManagedObject
)。对我来说,下一步是当
syncStatus
设置为.local
时,我还需要通过将其设置为-1来摆脱对象上的serverId
,但是尝试时出现了以下错误:extension Syncable where Self: RemoteObject {
var syncStatus: SyncStatus {
get {
SyncStatus(rawValue: syncStatusValue) ?? .local
}
set {
syncStatusValue = newValue.rawValue
if newValue == .local { serverId = -1 } // Cannot assign to property: 'self' is immutable
}
}
}
无法分配给属性:'self'是不可变的
我理解这个错误是因为RemoteObject
可以用于结构体,而结构体是不可变的。
然而,考虑到Syncable
只能应用于类类型,难道它不会强制使RemoteObject
应用于类?然后是可变的吗?
是否有一种方法可以在我的扩展中强制将RemoteObject
作为类类型?例如 extension Syncable where Self: RemoteObject & class
?
var s = self
会复制self
,但当然这不是情况,因为Syncable
总是一个类。所以,这只是为了让编译器静默。 - gcharitaXCTest
中尝试了一下,它完全正常。但这仍然困扰着我,因为错误不应该出现在我的 setter 的第一个版本上,因为它只能是引用类型。当我去掉class
或AnyObject
用于Syncable
时,错误才应该出现。 - Olympiloutre