featherless software design

View on GitHub
24 October 2015

Hashable Cfstring In Swift

by

Hashable CFString in Swift

This post is also available as a Swift playground at https://github.com/jverkoey/playgrounds.

If you find that you need to use a CFString in a Swift switch statement you’ll likely run into the following cryptic error:

Expression pattern of type 'CFString' cannot match values of type 'CFString'

or the slightly more helpful error when attempting to use a Set:

Type 'CFString' does not conform to protocol 'Hashable'

So let’s make CFString Hashable.

CFString+Hashable.swift

extension CFString : Hashable {
  public var hashValue: Int { return Int(CFHash(self)) }
}

public func ==(lhs: CFString, rhs: CFString) -> Bool {
  return CFStringCompare(lhs, rhs, CFStringCompareFlags()) == .CompareEqualTo
}

View the complete code on GitHub

tags: