上下文:值的数组,可以是 [Int]
或 [String]
- 但重要的是没有别的 - 并且也是可选的,需要与潜在的新值进行比较以检查先前是否存在。这是当前的解决方案:
protocol ValueType {}
extension Int: ValueType {}
extension String: ValueType {}
let values: [[ValueType]?] = []
// ...
values.append(["a", "b", "c"])
values.append([1, 2, 3, 4, 5])
在从数组中获取要比较的值之前,这工作正常,因此:
func compare(_ newValues: [ValueType]?, at index: Int) {
let existingValues = values[i]
let areTheSame = existingValues == newValues
}
当然,此时:
Protocol type 'ValueType' cannot conform to 'Equatable' because only concrete types can conform to protocols
你会如何解决这个问题?
最佳答案
我会通过不使用协议(protocol)来解决它。使 ValueType 成为联合,即具有两个具有关联值的案例的枚举。在现代 Swift 中,联合是相等的,数组的数组是相等的,问题就解决了。
关于arrays - 如何[最好]比较多类型[但仍然受控]数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58412503/