I am trying to initialize a class with an escaping closure inside my unit test, but it always crash with EXC_BAD_ACCESS (code=1, address=0x0)
. Here my code for declaring the class:
public class ListMock<T: HashDiffable & Equatable>: UICollectionView {
private let content: (T) -> UICollectionViewCell
public init(
collectionViewLayout: UICollectionViewLayout = UICollectionViewFlowLayout(),
content: @escaping (T) -> UICollectionViewCell
) {
self.content = content
super.init(
frame: .zero,
collectionViewLayout: collectionViewLayout
)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And here how I initialize ListMock
inside my unit test functions:
internal final class ListTests: XCTestCase {
internal func testBatchUpdateMoveWithDuplicateItems() {
let listNode = ListMock<ListNodeTestModel> { model in
model.generateListCellNode()
}
}
}
internal struct ListNodeTestModel: Equatable, HashDiffable {
internal let id: Int
internal var desc: String = ""
internal static func == (lhs: ListNodeTestModel, rhs: ListNodeTestModel) -> Bool {
return lhs.id == rhs.id && lhs.desc == rhs.desc
}
internal func generateListCellNode() -> UICollectionViewCell {
return UICollectionViewCell()
}
}
After some debugging, I found that the culprit is HashDiffable
protocol:
public protocol HashDiffable {
associatedtype IdentifierType: Hashable
var id: Self.IdentifierType { get }
func isEqual(to source: Self) -> Bool
}
public extension HashDiffable where Self: Hashable {
/// The `self` value as an identifier for difference calculation.
var id: Self {
return self
}
}
extension HashDiffable where Self: Equatable {
public func isEqual(to source: Self) -> Bool {
return self == source
}
}
But I am still not sure, why this protocol trigger this crash
Swift 5.9
Xcode 15.4