Created
April 19, 2020 21:27
-
-
Save McNight/c3a2b2bc3f047b09a1d1f3b27f8fb223 to your computer and use it in GitHub Desktop.
Hashable's StaticString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension StaticString: Equatable { | |
public static func == (lhs: StaticString, rhs: StaticString) -> Bool { | |
let lp = UnsafeRawPointer(lhs.utf8Start).assumingMemoryBound(to: Int8.self) | |
let rp = UnsafeRawPointer(rhs.utf8Start).assumingMemoryBound(to: Int8.self) | |
return strcmp(lp, rp) == 0 | |
} | |
} | |
extension StaticString: Hashable { | |
public func hash(into hasher: inout Hasher) { | |
hasher.combine(bytes: UnsafeRawBufferPointer(start: utf8Start, count: utf8CodeUnitCount)) | |
} | |
} | |
var dictionary: [StaticString: Int] = [:] | |
dictionary["Swift"] = 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just noting the above StaticString comparison will blow up if the StaticString is a unicode scalar. A safer method that also works with scalars is ...