Answer the question
In order to leave comments, you need to log in
How to use optional types implementing Equatable in generics?
By default, Swift defines functions that implement Equatable to work with optional types.
var pA: UnsafeMutableRawPointer?
var pB: UnsafeMutableRawPointer?
print(pA == pB);
protocol AdapterProtocol {
associatedtype IntegralType: Equatable
init(_ value: IntegralType)
}
// Всё отлично, UnsafeMutableRawPointer реализует Equatable
struct Adapter: AdapterProtocol {
var val: UnsafeMutableRawPointer
public init(_ value: UnsafeMutableRawPointer) {
val = value
}
}
// Ошибка: does not conform to 'Equatable'
struct AdapterOptional: AdapterProtocol {
var val: UnsafeMutableRawPointer?
public init(_ value: UnsafeMutableRawPointer?) {
val = value
}
}
Answer the question
In order to leave comments, you need to log in
Obviously, it needs to be satisfied Optional<UnsafeMutableRawPointer> : Equatable
. In theory, it should be enough to write:
extension Optional: Equatable where Wrapped: Equatable {
func == (lhs: Optional<Wrapped>, rhs: Optional<Wrapped>) -> Bool
}
struct EquatableWrapper<Wrapped: Equatable>: Equatable {
var wrapped: Wrapped?
init(_ newValue: Wrapped?) { wrapped = newValue }
}
func == <T: Equatable> (lhs: EquatableWrapper<T>, rhs: EquatableWrapper<T>) -> Bool {
return lhs.wrapped == rhs.wrapped
}
struct AdapterOptional: AdapterProtocol {
var val: UnsafeMutableRawPointer?
public init(_ value: EquatableWrapper<UnsafeMutableRawPointer>) {
self.val = value.wrapped
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question