[swift-evolution] URL Literals

David Sweeris davesweeris at mac.com
Tue Dec 20 14:29:29 CST 2016


> On Dec 20, 2016, at 2:11 AM, Jonathan Hull via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Yes, I agree.  I am excited to see what happens in phase 2.
> 
> What I am suggesting here is slightly different. Basically being able to use RegEx (with capture groups) as a shorthand for a type composed of base literals. For example: (StringLiteral, [IntegerLiteral]). Named capture groups could even map to a dictionary literal.  I am using “RegEx goes Here” to represent RegEx in the examples below, but hopefully it will get it’s own literal type in Xcode (Imagine that replacing it here).
> 
> 	func foo( _ param: “RegExGoesHere”) {…} //Definition uses a RegEx where the type would normally be
> 	foo(“my parseable string") //Calling with a string literal
> 
> In this case, ‘param’ takes a string literal when called but the compiler converts it to a tuple of literals based on the regEx supplied and passes that tuple the function. The type/structure of the tuple is defined by the capture groups in the RegEx
> 
> The parameter above would only allow string literals to be passed in, and would give a compiler error if you tried to pass a variable or if the string didn’t conform to the supplied RegEx.  To allow passing String variables you would have to add either ‘?’ or ‘!’ after the RegEx definition to handle the case where the value doesn’t conform.
> 
> 	func foo( _ param: “RegExGoesHere”?) {…} //‘param' is nil if RegEx fails
> 	foo(myStringVar) //Calling
> 
> 	func bar( _ param: “RegExGoesHere”!) {…} //fatal error if RegEx fails
> 
> When a variable is passed, the RegEx is performed at runtime instead of compile time.
> 
> Once you have this, the syntax to add new literal types/initializers falls out virtually for free.

Is “RegExGoesHere” where the regex pattern goes, or where the string you’re trying to match goes? If it’s the latter, where does the pattern go? If it’s the former, where does the string you’re trying to match go?

Also, it’s worth noting that I don’t think you can just use Strings to hold arbitrary regular expressions… According to “Daveo” (not me) on stackoverflow (http://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url), the regex for the regex for an URL is:
[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)
But pasting this into a string literal gives several “Invalid escape sequence in literal” errors.

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161220/756c9531/attachment.html>


More information about the swift-evolution mailing list