我需要任何 FileUpload
项 Equatable
类中的容器(例如,从故事板初始化的UI类)。我需要这样的
Generic
但它不起作用,var items: [Equatable]?
需要通用。存在普通Equatable
类的问题。
好的 - 转到通用!但如果我这样做
Equatable
然后我将被迫在我的nonGeneric-UI类中指定类型。喜欢这个
class Item<Value: Equatable>: Equatable {
var value: Value
init(_ value: Value) {
self.value = value
}
//Equatable
public static func ==(lhs: Item, rhs: Item) -> Bool {
return (lhs.value == rhs.value)
}
}
但我们又遇到了一个问题,即没有共同的var items: [Item<WhatShouldBeHere?>]?
类
All Equatable容器的任何解决方案?
答案 0 :(得分:4)
代替存在类型,您需要使用类型橡皮擦:
public struct AnyEquatable: Equatable {
public let value: Any
private let equals: (Any) -> Bool
public init<E: Equatable>(_ value: E) {
self.value = value
self.equals = { ($0 as? E) == value }
}
public static func == (lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
return lhs.equals(rhs.value) || rhs.equals(lhs.value)
}
}
示例用法:
let items = [
AnyEquatable(1),
AnyEquatable(1.23),
AnyEquatable(true),
AnyEquatable("some string")
]
let desired = "some string"
let desiredAsAnyEquatable = AnyEquatable(desired)
let desiredDescription = String(reflecting: desired)
for item in items {
let itemDescription = String(reflecting: item.value)
let isEqualToDesired = item == desiredAsAnyEquatable
print("\(itemDescription) is \(isEqualToDesired ? "": "not ")equal to \(desiredDescription)")
}
示例输出:
1不等于“some string”
1.23不等于“some string”
true不等于“some string”
“some string”等于“some string”