Skip to content

Instantly share code, notes, and snippets.

@kourge
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save kourge/3f8a7fc31a1cb73709c7 to your computer and use it in GitHub Desktop.

Select an option

Save kourge/3f8a7fc31a1cb73709c7 to your computer and use it in GitHub Desktop.
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"
@mgadda
Copy link

mgadda commented Jun 4, 2014

C'mon GitHub, Swift has been out for 24 hours already. Where is the syntax highlighting? Pffffff.

@kourge
Copy link
Author

kourge commented Jun 4, 2014

The funny thing is Github lets me select Swift as the language but as soon as I save the gist, it reverts back to Text.

@zlangley
Copy link

zlangley commented Jun 5, 2014

Wow, no length method on Strings? Also, why NSRegularExpression! instead of just NSRegularExression?

@kourge
Copy link
Author

kourge commented Jun 5, 2014

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