我有一个Equatable
class
class Item: Equatable {
var value: AnyObject?
var title: String
init(title: String, value: AnyObject?) {
self.title = title
self.value = value
}
//Equatable
public static func ==(lhs: Item, rhs: Item) -> Bool {
return ((lhs.title == rhs.title) && (lhs.value === rhs.value))
}
}
但我想尝试 varvalue
到 Equatable,这样就得到软可等结果
if let lValue = lhs.value as? Equatable, // Error
let rValue = rhs.value as? Equatable { // Error
valueEq = (lValue == rValue)
} else {
valueEq = (lhs.value === rhs.value)
}
此代码捕获有关 Generic Equatable 的编译错误
我怎样才能为这门课做正确的 Equatable?
UPD
我想用我的Item
in UITableViewCell
在我的故事板中。我无法创建通用的UITableViewCell
。如果我尝试做 Item 作为Generic<T: Equatable>
类,我将被迫指定我的单元格中的类型,
var items: [Item<OnlyThisHashableClass>]
但我想对任何对象使用单元格中的项目
简单的方法 - 类保留 NonGeneric,仅 Genericinit
,并在 GenericInit 中创建 isEquals 方法
class FieldItem: CustomStringConvertible, Equatable {
let value: Any?
let title: String
private let equals: (Any?) -> Bool
init<Value: Equatable>(title: String, value: Value?) {
func isEquals(_ other: Any?) -> Bool {
if let l = value, let r = other {
if let r = r as? Value {
return l == r
} else {
return false
}
} else {
return true
}
}
self.title = title
self.value = value
self.equals = isEquals
}
//CustomStringConvertible
var description: String { get { return title } }
//Equatable
public static func ==(lhs: FieldItem, rhs: FieldItem) -> Bool {
return ((lhs.title == rhs.title) && lhs.equals(rhs.value))
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)