Xcode downloaded a crash report for my app that crashed when trying to insert a String
into a Set<String>
. Apparently there was an assertion failure ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS
. I assume that this assertion failure happened because the hash of the new element didn't match the hash of an equal already inserted element, but regardless, I don't understand how inserting a simple string could trigger this assertion.
Here is essentially the code that leads to the crash. path
is any file system directory, and basePath
is a directory higher in the hierarchy, or path
itself.
var scanErrorPaths = Set<String>()
func main() {
let path = "/path/to/directory"
let basePath = "/path"
let fileDescriptor = open(path, O_RDONLY)
if fileDescriptor < 0 {
if (try? URL(fileURLWithPath: path, isDirectory: false).checkResourceIsReachable()) == true {
scanErrorPaths.insert(path.relativePath(from: basePath)!)
return
}
}
extension String {
func relativePath(from basePath: String) -> String? {
if basePath == "" {
return self
}
guard let index = range(of: basePath, options: .anchored)?.upperBound else {
return nil
}
return if index == endIndex || basePath == "/" {
String(self[index...])
} else if let index = self[index...].range(of: "/", options: .anchored)?.upperBound {
String(self[index...])
} else {
nil
}
}
}