Skip to content

Instantly share code, notes, and snippets.

@zakbarlow1995
Last active July 24, 2019 09:35
Show Gist options
  • Save zakbarlow1995/4850d7723989958c29ba5951d1445bd3 to your computer and use it in GitHub Desktop.
Save zakbarlow1995/4850d7723989958c29ba5951d1445bd3 to your computer and use it in GitHub Desktop.
String extension to add a regex comparison operator "~="
import Foundation
extension String {
static func ~= (lhs: String, rhs: String) -> Bool {
guard let regex = try? NSRegularExpression(pattern: rhs) else { return false }
let range = NSRange(location: 0, length: lhs.utf16.count)
return regex.firstMatch(in: lhs, options: [], range: range) != nil
}
}
@zakbarlow1995
Copy link
Author

zakbarlow1995 commented Jul 23, 2019

Example usage, checking a(n error) string to see if it contains a HTTP status code:

extension String {
    func contains(statusCode: StatusCode) -> Bool {
        return self ~= "\\b\(statusCode.rawValue)[0-9][0-9]\\b"
    }
}

enum StatusCode: Int, CaseIterable {
    case oneHundred = 1, twoHundred, threeHundred, fourHundred, fiveHundred
}

Usage:

// Thrown error contains status code 400-499
if errorString.contains(statusCode: .fourHundred) {
    // Do something...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment