Last active
August 29, 2015 14:02
-
-
Save kourge/3f8a7fc31a1cb73709c7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| operator prefix ~ {} | |
| @prefix func ~(pattern: String) -> NSRegularExpression! { | |
| var error: NSError? | |
| return NSRegularExpression.regularExpressionWithPattern( | |
| pattern, | |
| options: nil, | |
| error: &error) | |
| } | |
| func ~=(pattern: NSRegularExpression, value: String) -> Bool { | |
| let range = NSMakeRange(0, value.bridgeToObjectiveC().length) | |
| return pattern.numberOfMatchesInString(value, options: nil, range: range) > 0 | |
| } | |
| func typeOf(v: String) -> String { | |
| switch v { | |
| case ~"[0-9]+": | |
| return "numeric" | |
| case ~"[a-zA-Z]": | |
| return "alpha" | |
| default: | |
| return "unknown" | |
| } | |
| } | |
| typeOf("9100") | |
| ~"[a-zA-Z][a-zA-Z0-9_$]" ~= "pelham_123" |
Author
NSRegularExpression.regularExpressionWithPattern returns an NSRegularExpression! and I suspect this is an Objective-C bridging convention on Swift's part, i.e. all initializer methods return Self!
Swift's built-in String type strangely does not have a length method, but it does have lengthOfBytesUsingEncoding(encoding: NSStringEncoding). Maybe they're trying to prevent string length miscalculations (Ruby 1.8.x deals with Unicode strings poorly) without mandating the encoding (e.g. Go enforces UTF-8) to anything specific.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, no length method on
Strings? Also, whyNSRegularExpression!instead of justNSRegularExression?