Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Pierre Monod-Broca via swift-evolution
But for a struct to be immutable, you don't need all its properties to be let. 
(I guess that's Derrick's point)

´´´
struct Person { /* . . . var properties . . . */ }
let john = Person() // john is completely immutable
´´´

If a struct has var properties, you can do a mutable copy, change it, assign it 
to a new let, and you take advantage of immutability again.

´´´
let jim = { var copy = john
  copy.firstname = "Jim"
  return copy
}()

func with(_ original: T, transform: (inout T) -> ()) -> T {
  var copy = original
  transform()
  return copy
}

let jane = with(john) { $0.firstname = "Jane" }
// jane is also immutable
´´´
(I didn't check this compiles)

Pierre

> Le 19 déc. 2016 à 23:08, Andy Chou via swift-evolution 
>  a écrit :
> 
> Value semantics help reduce the issues around mutability, but they don't go 
> away completely. I would like to create structs that are completely immutable 
> after construction. Turning the properties into vars unfortunately loses this 
> idea.
> 
> The proposed 'with' function doesn't construct new instances, which means the 
> let constants are already set. Nick's solution works, as it's basically a 
> copy constructor that allows for changes while the new object is constructed. 
> But it needs to be created for each struct. Which I'm fine with :)
> 
> Andy
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Swift Closure still inconsistent -- tuple names need to be in curly brackets, single parameter needs to be in parentheses

2016-12-19 Thread Vip Malixi via swift-evolution
Choice for choice's sake as in 100s of ways to do the same thing leads to 
confusion and complexity. My suggestions are to make Swift consistent, simple, 
and clear. As it is right now, the motives to keep things status quo in Swift 
are the same reasons MS Windows was more difficult to use than the Mac OS: 
hundreds of unintuitive ways to do the same thing added by programmers without 
concern for simplicity, ease-of-use and elegance.
V. Malixi

 
  From: Anton Zhilin 
 To: Derrick Ho  
Cc: Vip Malixi ; Xiaodi Wu ; 
"swift-evolution@swift.org" 
 Sent: Tuesday, December 20, 2016 6:15 AM
 Subject: Re: [swift-evolution] Swift Closure still inconsistent -- tuple names 
need to be in curly brackets, single parameter needs to be in parentheses
   
2016-12-20 0:59 GMT+03:00 Derrick Ho :
The core team designed swift blocks to range from concise to verbose. Which one 
you use depends on your needs.

If you want to write parenthesis then by all means write parenthesis; no one is 
stopping you.

I would rather keep the block syntax as it is so that everyone can choose the 
style that matches their needs.
On Mon, Dec 19, 2016 at 1:52 PM Xiaodi Wu via swift-evolution 
 wrote:

This issue about `numbers in` was raised during review of SE-0066; if I recall, 
the core team considered and rejected disallowing that syntax in closures. 
Since we're minimizing source-breaking changes, the issue is settled in my 
view, having been proposed, commented upon, reviewed, and rejected.

Ok, I understand, you probably consider the syntax in question { param -> Int 
in ... } closer to the short form { param in ... } than to the full form { 
(param: Int) -> Int in ... }So when applying analogy, it makes more sense to 
allow the omission as in the short form than to disallow as in the full form. I 
have to agree. So, -1 to all points of the OP.​

   
 ___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Erica Sadun via swift-evolution
Regex is another thing that appears on many platforms and has a standard way to 
express it.

-- E

> On Dec 19, 2016, at 5:51 PM, Jonathan Hull  wrote:
> 
> +1 to Erica’s literal extensions (and Xiaodi’s idea of showing Favicons in 
> Xcode where possible)
> 
> Perhaps the easiest way to allow arbitrary literal extensions beyond those 
> would be, in phase 2 when we add RegEx to the language, to take a RegEx 
> defining the custom literal and have the compiler output a tuple of other 
> literal types (including array literals for ‘*’, etc...) to the init method 
> as a result of parsing it.
> 
> It would actually be interesting to have the parsing via RegEx into literals 
> as a general feature for parameters, and then the init syntax would fall out 
> basically for free...
> 
> Thanks,
> Jon
> 
> 
>> On Dec 18, 2016, at 2:17 PM, Erica Sadun via swift-evolution 
>> > wrote:
>> 
>> I'd prefer to see a literal URL than a Foundation URL that is 
>> string-initializable. I don't see a URL literal as being in any way 
>> necessarily tightly coupled with a Foundation URL type. The point of a 
>> literal is that it is inherently typeless and checked at compile time. A 
>> color literal depending on context can be a UIColor or NSColor but that's 
>> not specified outside of the use context. The code is portable and cross 
>> platform.
>> 
>> -- E
>> 
>> 
>>> On Dec 17, 2016, at 10:18 PM, Xiaodi Wu via swift-evolution 
>>> > wrote:
>>> 
>>> With respect to URL specifically, that it's a Foundation type may change 
>>> the timeline as well. Various improvements to the Foundation API (and URL 
>>> in particular) have been proposed here, but if I remember correctly, the 
>>> stated goal was first to have a complete Swift version of Foundation, 
>>> preserving the existing API as exactly as possible with no additions or 
>>> subtractions, and only then to consider Swifty evolution of the APIs. I 
>>> don't think the first step is complete yet.
>>> 
>>> On Sat, Dec 17, 2016 at 21:46 Step C via swift-evolution 
>>> > wrote:
>>> Probably worth pointing out that this topic seems entirely additive. Which 
>>> means it would be at least a phase 2 proposal, if not later.
>>> 
>>> > On Dec 17, 2016, at 4:44 PM, Micah Hainline via swift-evolution 
>>> > > wrote:
>>> >
>>> > Yes, everyone who has what they feel like is a solid workable solution 
>>> > should write it up for URL and we can compare and pick holes in them all 
>>> > until we get something really solid.
>>> >
>>> >> On Dec 17, 2016, at 3:27 PM, David Sweeris >> >> > wrote:
>>> >>
>>> >>
>>> >>
>>> >> Sent from my iPhone
>>> >>
>>> >>> On Dec 17, 2016, at 13:20, David Sweeris >> >>> > wrote:
>>> >>>
>>> >>>
>>> >>>
>>> >>> Sent from my iPhone
>>> >>>
>>>  On Dec 17, 2016, at 13:12, Micah Hainline via swift-evolution 
>>>  > wrote:
>>> 
>>>  I'd love a fleshed out elegant example for URL that shows what a 
>>>  complete implementation of that special init method would look like.
>>> >>>
>>> >>> I can't do it now, but I'll try post one before tomorrow that shows how 
>>> >>> I'd envision it working.
>>> >>
>>> >> Oh, and to be clear, I'm not trying to "claim" this or anything... if 
>>> >> anyone else has ideas, please post them! The more the merrier.
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
I believe regex was one of the topics that the core team proposed was a
possibility for phase 2. I too am eager to hear what they have in mind.
On Mon, Dec 19, 2016 at 23:02 Erica Sadun  wrote:

> Regex is another thing that appears on many platforms and has a standard
> way to express it.
>
> -- E
>
> On Dec 19, 2016, at 5:51 PM, Jonathan Hull  wrote:
>
> +1 to Erica’s literal extensions (and Xiaodi’s idea of showing Favicons in
> Xcode where possible)
>
> Perhaps the easiest way to allow arbitrary literal extensions beyond those
> would be, in phase 2 when we add RegEx to the language, to take a RegEx
> defining the custom literal and have the compiler output a tuple of other
> literal types (including array literals for ‘*’, etc...) to the init method
> as a result of parsing it.
>
> It would actually be interesting to have the parsing via RegEx into
> literals as a general feature for parameters, and then the init syntax
> would fall out basically for free...
>
> Thanks,
> Jon
>
>
> On Dec 18, 2016, at 2:17 PM, Erica Sadun via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I'd prefer to see a literal URL than a Foundation URL that is
> string-initializable. I don't see a URL literal as being in any way
> necessarily tightly coupled with a Foundation URL type. The point of a
> literal is that it is inherently typeless and checked at compile time. A
> color literal depending on context can be a UIColor or NSColor but that's
> not specified outside of the use context. The code is portable and cross
> platform.
>
> -- E
>
>
> On Dec 17, 2016, at 10:18 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> With respect to URL specifically, that it's a Foundation type may change
> the timeline as well. Various improvements to the Foundation API (and URL
> in particular) have been proposed here, but if I remember correctly, the
> stated goal was first to have a complete Swift version of Foundation,
> preserving the existing API as exactly as possible with no additions or
> subtractions, and only then to consider Swifty evolution of the APIs. I
> don't think the first step is complete yet.
>
> On Sat, Dec 17, 2016 at 21:46 Step C via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Probably worth pointing out that this topic seems entirely additive. Which
> means it would be at least a phase 2 proposal, if not later.
>
> > On Dec 17, 2016, at 4:44 PM, Micah Hainline via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Yes, everyone who has what they feel like is a solid workable solution
> should write it up for URL and we can compare and pick holes in them all
> until we get something really solid.
> >
> >> On Dec 17, 2016, at 3:27 PM, David Sweeris  wrote:
> >>
> >>
> >>
> >> Sent from my iPhone
> >>
> >>> On Dec 17, 2016, at 13:20, David Sweeris  wrote:
> >>>
> >>>
> >>>
> >>> Sent from my iPhone
> >>>
>  On Dec 17, 2016, at 13:12, Micah Hainline via swift-evolution <
> swift-evolution@swift.org> wrote:
> 
>  I'd love a fleshed out elegant example for URL that shows what a
> complete implementation of that special init method would look like.
> >>>
> >>> I can't do it now, but I'll try post one before tomorrow that shows
> how I'd envision it working.
> >>
> >> Oh, and to be clear, I'm not trying to "claim" this or anything... if
> anyone else has ideas, please post them! The more the merrier.
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Daniel Leping via swift-evolution
I was thinking about a possibility to extend the language itself with
custom literals. It should cover quite some stuff including URL, Regex, etc.

Just add an extended operator-ish syntax. Can be done with regular
expressions or similar.

//RegexLiteralDefinition
literal /(.*)/(.*)/ (regex:String, flags:String) -> RegexLiteralProtocol {
//code of construction here
}

//Use
let regex = /myregex/g/

//URLLiteralDefinition
literal u"(.*)" (url:String) -> URLLiteralProtocol {
//code of construction here
}

//use
let url = u"http://swift.org/;

This way we can add more literals later without compiler modifications.

If this gets any support I can create a draft of the spec for the feature.

On Tue, 20 Dec 2016 at 6:21 Jonathan Hull via swift-evolution <
swift-evolution@swift.org> wrote:

> +1 to Erica’s literal extensions (and Xiaodi’s idea of showing Favicons in
> Xcode where possible)
>
> Perhaps the easiest way to allow arbitrary literal extensions beyond those
> would be, in phase 2 when we add RegEx to the language, to take a RegEx
> defining the custom literal and have the compiler output a tuple of other
> literal types (including array literals for ‘*’, etc...) to the init method
> as a result of parsing it.
>
> It would actually be interesting to have the parsing via RegEx into
> literals as a general feature for parameters, and then the init syntax
> would fall out basically for free...
>
> Thanks,
> Jon
>
>
> On Dec 18, 2016, at 2:17 PM, Erica Sadun via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I'd prefer to see a literal URL than a Foundation URL that is
> string-initializable. I don't see a URL literal as being in any way
> necessarily tightly coupled with a Foundation URL type. The point of a
> literal is that it is inherently typeless and checked at compile time. A
> color literal depending on context can be a UIColor or NSColor but that's
> not specified outside of the use context. The code is portable and cross
> platform.
>
> -- E
>
>
> On Dec 17, 2016, at 10:18 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> With respect to URL specifically, that it's a Foundation type may change
> the timeline as well. Various improvements to the Foundation API (and URL
> in particular) have been proposed here, but if I remember correctly, the
> stated goal was first to have a complete Swift version of Foundation,
> preserving the existing API as exactly as possible with no additions or
> subtractions, and only then to consider Swifty evolution of the APIs. I
> don't think the first step is complete yet.
>
> On Sat, Dec 17, 2016 at 21:46 Step C via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Probably worth pointing out that this topic seems entirely additive. Which
> means it would be at least a phase 2 proposal, if not later.
>
>
>
>
>
> > On Dec 17, 2016, at 4:44 PM, Micah Hainline via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> >
>
>
> > Yes, everyone who has what they feel like is a solid workable solution
> should write it up for URL and we can compare and pick holes in them all
> until we get something really solid.
>
>
> >
>
>
> >> On Dec 17, 2016, at 3:27 PM, David Sweeris  wrote:
>
>
> >>
>
>
> >>
>
>
> >>
>
>
> >> Sent from my iPhone
>
>
> >>
>
>
> >>> On Dec 17, 2016, at 13:20, David Sweeris  wrote:
>
>
> >>>
>
>
> >>>
>
>
> >>>
>
>
> >>> Sent from my iPhone
>
>
> >>>
>
>
>  On Dec 17, 2016, at 13:12, Micah Hainline via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> 
>
>
>  I'd love a fleshed out elegant example for URL that shows what a
> complete implementation of that special init method would look like.
>
>
> >>>
>
>
> >>> I can't do it now, but I'll try post one before tomorrow that shows
> how I'd envision it working.
>
>
> >>
>
>
> >> Oh, and to be clear, I'm not trying to "claim" this or anything... if
> anyone else has ideas, please post them! The more the merrier.
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> ___
>
> swift-evolution mailing list
>
> swift-evolution@swift.org
>
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Jonathan Hull via swift-evolution
+1 to Erica’s literal extensions (and Xiaodi’s idea of showing Favicons in 
Xcode where possible)

Perhaps the easiest way to allow arbitrary literal extensions beyond those 
would be, in phase 2 when we add RegEx to the language, to take a RegEx 
defining the custom literal and have the compiler output a tuple of other 
literal types (including array literals for ‘*’, etc...) to the init method as 
a result of parsing it.

It would actually be interesting to have the parsing via RegEx into literals as 
a general feature for parameters, and then the init syntax would fall out 
basically for free...

Thanks,
Jon


> On Dec 18, 2016, at 2:17 PM, Erica Sadun via swift-evolution 
>  wrote:
> 
> I'd prefer to see a literal URL than a Foundation URL that is 
> string-initializable. I don't see a URL literal as being in any way 
> necessarily tightly coupled with a Foundation URL type. The point of a 
> literal is that it is inherently typeless and checked at compile time. A 
> color literal depending on context can be a UIColor or NSColor but that's not 
> specified outside of the use context. The code is portable and cross platform.
> 
> -- E
> 
> 
>> On Dec 17, 2016, at 10:18 PM, Xiaodi Wu via swift-evolution 
>> > wrote:
>> 
>> With respect to URL specifically, that it's a Foundation type may change the 
>> timeline as well. Various improvements to the Foundation API (and URL in 
>> particular) have been proposed here, but if I remember correctly, the stated 
>> goal was first to have a complete Swift version of Foundation, preserving 
>> the existing API as exactly as possible with no additions or subtractions, 
>> and only then to consider Swifty evolution of the APIs. I don't think the 
>> first step is complete yet.
>> 
>> On Sat, Dec 17, 2016 at 21:46 Step C via swift-evolution 
>> > wrote:
>> Probably worth pointing out that this topic seems entirely additive. Which 
>> means it would be at least a phase 2 proposal, if not later.
>> 
>> > On Dec 17, 2016, at 4:44 PM, Micah Hainline via swift-evolution 
>> > > wrote:
>> >
>> > Yes, everyone who has what they feel like is a solid workable solution 
>> > should write it up for URL and we can compare and pick holes in them all 
>> > until we get something really solid.
>> >
>> >> On Dec 17, 2016, at 3:27 PM, David Sweeris > >> > wrote:
>> >>
>> >>
>> >>
>> >> Sent from my iPhone
>> >>
>> >>> On Dec 17, 2016, at 13:20, David Sweeris > >>> > wrote:
>> >>>
>> >>>
>> >>>
>> >>> Sent from my iPhone
>> >>>
>>  On Dec 17, 2016, at 13:12, Micah Hainline via swift-evolution 
>>  > wrote:
>> 
>>  I'd love a fleshed out elegant example for URL that shows what a 
>>  complete implementation of that special init method would look like.
>> >>>
>> >>> I can't do it now, but I'll try post one before tomorrow that shows how 
>> >>> I'd envision it working.
>> >>
>> >> Oh, and to be clear, I'm not trying to "claim" this or anything... if 
>> >> anyone else has ideas, please post them! The more the merrier.
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Swift Closure still inconsistent -- tuple names need to be in curly brackets, single parameter needs to be in parentheses

2016-12-19 Thread Anton Zhilin via swift-evolution
2016-12-20 0:59 GMT+03:00 Derrick Ho :

The core team designed swift blocks to range from concise to verbose. Which
> one you use depends on your needs.
>
> If you want to write parenthesis then by all means write parenthesis; no
> one is stopping you.
>
> I would rather keep the block syntax as it is so that everyone can choose
> the style that matches their needs.
>
> On Mon, Dec 19, 2016 at 1:52 PM Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> This issue about `numbers in` was raised during review of SE-0066; if I
>> recall, the core team considered and rejected disallowing that syntax in
>> closures. Since we're minimizing source-breaking changes, the issue is
>> settled in my view, having been proposed, commented upon, reviewed, and
>> rejected.
>
> Ok, I understand, you probably consider the syntax in question { param ->
Int in ... } closer to the short form { param in ... } than to the full
form { (param: Int) -> Int in ... }

So when applying analogy, it makes more sense to allow the omission as in
the short form than to disallow as in the full form. I have to agree. So,
-1 to all points of the OP.
​
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Xiaodi Wu via swift-evolution
More advanced mirroring is one of those things that is on the agenda
somewhere. It would stand to reason that a generalizable solution which
doesn't need to be created for each struct would become possible when that
arrives, no?

On Mon, Dec 19, 2016 at 16:08 Andy Chou via swift-evolution <
swift-evolution@swift.org> wrote:

> Value semantics help reduce the issues around mutability, but they don't
> go away completely. I would like to create structs that are completely
> immutable after construction. Turning the properties into vars
> unfortunately loses this idea.
>
> The proposed 'with' function doesn't construct new instances, which means
> the let constants are already set. Nick's solution works, as it's basically
> a copy constructor that allows for changes while the new object is
> constructed. But it needs to be created for each struct. Which I'm fine
> with :)
>
> Andy
>
> On Dec 19, 2016, at 1:47 PM, Derrick Ho  wrote:
>
> That is correct Andy. Let-constant can not be assigned a new value after
> it gets its initial value.
>
> It is unclear why you are against turning your properties into var's.
> Because you are using structs, all properties are copied by value.
>
> struct Person {
>   var name: String
> }
>
> let andy = Person(name: "Andy")
> var brandon = andy; brandon.name = "Brandon"
>
> andy.name // "Andy"
> brandon.name // "Brandon"
>
> I believe this accomplishes the same thing you wanted in with(name:)
>
> On Mon, Dec 19, 2016 at 1:26 PM Andy Chou via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Thanks Erica, I wasn't aware of that Swift evolution proposal. If I'm
> reading it right, this wouldn't work with structs with let-variables...?
> Here's what I get with this example:
>
> struct Person {
> let name: String
> let address: String
> }
>
> @discardableResult
> public func with(_ item: T, update:
> (inout T) throws -> Void) rethrows -> T {
> var this = item
> try update()
> return this
> }
>
> let john = Person(name: "John", address: "1 battery st")
> let jane: Person = with(john) { $0.name = "Jane" } //
> Test.swift:24:41: Cannot assign to property: 'name' is a 'let' constant
>
> Andy
>
>
> On Dec 19, 2016, at 11:44 AM, Erica Sadun  wrote:
>
> https://github.com/apple/swift-evolution/pull/346
>
> Be aware that there's a bug that's being worked on:
>
> https://bugs.swift.org/browse/SR-2773
>
> -- E
>
>
> On Dec 19, 2016, at 12:40 PM, Andy Chou via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Of course. Thanks for pointing out the obvious solution. This preserves
> the immutability of the struct and doesn't require O(n^2) code for structs
> with large numbers of fields.
>
> I was thinking of a generic solution - perhaps something like a synthetic
> initializer that does what your solution does. But that may be overkill
> given how relatively easy it is to do this per struct...
>
> On the other hand a generic solution would encourage using immutable
> structs. I wasted too much time trying to solve this, I suspect others
> would just give up and use var, or even classes.
>
> Andy
>
> On Dec 19, 2016, at 10:43 AM, Nick Keets  wrote:
>
>
>
>
>
>
>
>
>
>
>
> You are probably asking for a generic solution, but for a specific struct
> you can implement it like this:
>
>
>
>
> extension Person {
> func with(name: String? = nil, address: String? = nil, phone: String?
> = nil) -> Person {
> let name = name ?? self.name
> let address = address ?? self.address
> let phone = phone ?? self.phone
> return Person(name: name, address: address, phone: phone)
> }
> }
>
>
>
>
>
>
>
>
>
>
>
>
> On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution <
> swift-evolution@swift.org>, wrote:
>
>
> I like that structs are value types in Swift, this encourages the use of
> immutable data. O'Caml has an operator "with" that allows for copying an
> existing struct with a change to one field. I looked at Lenses for this
> functionality and it seems like a lot to digest for something so simple. I
> also tried to implement this using a constructor, or a function, and it was
> not obvious how to do so without a lot of code duplication.
>
>
>
>
>
> What's I'm looking for is something like this (not necessarily with this
> syntax):
>
>
>
>
>
> struct Person {
>
>
> let name: String
>
>
> let address: String
>
>
> let phone: String
>
>
> }
>
>
>
>
>
> func f() {
>
>
> let andy = Person(name: "Andy", address: "1 Battery St., San Francisco,
> CA", phone: "1234567")
>
>
> let chris = andy.with(name: "Chris")
>
>
> let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
>
>
> }
>
>
>
>
>
> I tried to implement a "with" function like this but default arguments
> cannot reference properties of self. Same problem trying to do this in a
> constructor.
>
>
>
>
>
> Obviously it's possible to create an entirely new Person specifying the
> values from an existing 

Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Andy Chou via swift-evolution
Value semantics help reduce the issues around mutability, but they don't go 
away completely. I would like to create structs that are completely immutable 
after construction. Turning the properties into vars unfortunately loses this 
idea.

The proposed 'with' function doesn't construct new instances, which means the 
let constants are already set. Nick's solution works, as it's basically a copy 
constructor that allows for changes while the new object is constructed. But it 
needs to be created for each struct. Which I'm fine with :)

Andy

> On Dec 19, 2016, at 1:47 PM, Derrick Ho  wrote:
> 
> That is correct Andy. Let-constant can not be assigned a new value after it 
> gets its initial value.
> 
> It is unclear why you are against turning your properties into var's.  
> Because you are using structs, all properties are copied by value.
> 
> struct Person {
>   var name: String
> }
> 
> let andy = Person(name: "Andy")
> var brandon = andy; brandon.name  = "Brandon"
> 
> andy.name  // "Andy"
> brandon.name  // "Brandon"
> 
> I believe this accomplishes the same thing you wanted in with(name:)
> 
> On Mon, Dec 19, 2016 at 1:26 PM Andy Chou via swift-evolution 
> > wrote:
> Thanks Erica, I wasn't aware of that Swift evolution proposal. If I'm reading 
> it right, this wouldn't work with structs with let-variables...?  Here's what 
> I get with this example:
> 
> struct Person {
> let name: String
> let address: String
> }
> 
> @discardableResult
> public func with(_ item: T, update: (inout T) throws -> Void) rethrows -> 
> T {
> var this = item
> try update()
> return this
> }
> 
> let john = Person(name: "John", address: "1 battery st")
> let jane: Person = with(john) { $0.name  = "Jane" } // 
> Test.swift:24:41: Cannot assign to property: 'name' is a 'let' constant
> 
> Andy
> 
> 
>> On Dec 19, 2016, at 11:44 AM, Erica Sadun > > wrote:
>> 
>> https://github.com/apple/swift-evolution/pull/346 
>> 
>> 
>> Be aware that there's a bug that's being worked on:
>> 
>> https://bugs.swift.org/browse/SR-2773 
>> 
>> -- E
>> 
>> 
>>> On Dec 19, 2016, at 12:40 PM, Andy Chou via swift-evolution 
>>> > wrote:
>>> 
>>> Of course. Thanks for pointing out the obvious solution. This preserves the 
>>> immutability of the struct and doesn't require O(n^2) code for structs with 
>>> large numbers of fields. 
>>> 
>>> I was thinking of a generic solution - perhaps something like a synthetic 
>>> initializer that does what your solution does. But that may be overkill 
>>> given how relatively easy it is to do this per struct...
>>> 
>>> On the other hand a generic solution would encourage using immutable 
>>> structs. I wasted too much time trying to solve this, I suspect others 
>>> would just give up and use var, or even classes. 
>>> 
>>> Andy
>>> 
>>> On Dec 19, 2016, at 10:43 AM, Nick Keets >> > wrote:
>>> 
 
 
 
 
 
 
 
 
 
 
 You are probably asking for a generic solution, but for a specific struct 
 you can implement it like this:
 
 
 
 
 extension Person {
 func with(name: String? = nil, address: String? = nil, phone: String? 
 = nil) -> Person {
 let name = name ?? self.name
 let address = address ?? self.address
 let phone = phone ?? self.phone
 return Person(name: name, address: address, phone: phone)
 }
 }
 
 
 
 
 
 
 
 
 
 
 
 
 On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution 
 >, wrote:
 
 
> I like that structs are value types in Swift, this encourages the use of 
> immutable data. O'Caml has an operator "with" that allows for copying an 
> existing struct with a change to one field. I looked at Lenses for this 
> functionality and it seems like a lot to digest for something so simple. 
> I also tried to implement this using a constructor, or a function, and it 
> was not obvious how to do so without a lot of code duplication.
> 
> 
> 
> 
> 
> What's I'm looking for is something like this (not necessarily with this 
> syntax):
> 
> 
> 
> 
> 
> struct Person {
> 
> 
> let name: String
> 
> 
> let address: String
> 
> 
> let phone: String
> 
> 
> }
> 
> 
> 
> 
> 
> func f() {
> 
> 
> let andy = Person(name: "Andy", address: "1 Battery St., San 

Re: [swift-evolution] [Pitch] Changing NSObject dispatch behavior

2016-12-19 Thread Charles Srstka via swift-evolution
> On Dec 19, 2016, at 1:57 PM, Kevin Ballard  wrote:
> 
> On Fri, Dec 16, 2016, at 06:30 AM, Charles Srstka wrote:
>>> On Dec 16, 2016, at 12:36 AM, Kevin Ballard >> > wrote:
>>> 
>>> On Thu, Dec 15, 2016, at 03:01 PM, Charles Srstka wrote:
> On Dec 15, 2016, at 4:33 PM, Kevin Ballard  > wrote:
> 
> The problem with that code isn't that `dynamic` doesn't work for computed 
> properties. It does; if you mutate the `foo` property, you'll get the KVO 
> notifications. The problem is you have one property that depends on 
> another and you didn't set up the KVO machinery properly using 
> automaticallyNotifiesObservers(forKey:) or 
> automaticallyNotifiesObserversOf() (incidentally in Swift you can 
> write the latter as a `static let`, since that becomes a class method in 
> Obj-C).
 
 You’ll only get the notifications if you mutate ‘foo’ directly. This, 
 however, is fairly useless, because if you are watching ‘foo’, you want to 
 be notified every time the value changes, not just when someone hits one 
 particular accessor. Code relying on observation of ‘foo’ in the example I 
 provided would be prone to breaking in mysterious and possibly horrible 
 ways.
>>> 
>>> No, if you implement keyPathsForValuesAffecting() then you get "foo" 
>>> KVO notifications when "bar" is mutated.  That's the whole point of that 
>>> method, and this is exactly what you have to do in Obj-C as well.
>> 
>> Right… the sentence I was quoting was talking about code which uses 
>> ‘dynamic’ but *doesn’t* use keyPathsForValuesAffecting. You’ll get 
>> notifications if someone calls that one particular accessor, but otherwise 
>> you won’t.
> 
> You can always write buggy code. If you're using `dynamic` for KVO purposes, 
> then not implementing keyPathsForValuesAffecting in this case is 
> strictly a bug. If you're using `dynamic` for something other than KVO, and 
> your property won't end up supporting KVO properly by default, then you 
> should document it as such, given that the natural assumption for a `dynamic` 
> property is that it supports KVO.

If you’re using ‘dynamic’ for KVO purposes, you should document it as such. If 
you are using it for something else, not implementing KVO is not in any way a 
bug. Relying on KVO for properties that are not documented to be compliant, 
though, *is.*

Documentation is the only reliable way to check for KVO conformance. I have a 
class with 28 KVO-compliant methods on it. Of those, exactly 4 are marked as 
‘dynamic’. The presence of the ‘dynamic’ keyword is not a good thing to rely on 
for this (and the lack of a good built-in mechanism is part of why, IMO, we 
need something new to replace KVO).

> So yes, `dynamic` by itself doesn't mean that the property supports KVO. 
> But there are very few reasons to use `dynamic` outside of supporting 
> KVO, so it's a pretty good signal that the property does support it. And 
> conversely, not having `dynamic` doesn't mean that it doesn't support 
> KVO, though if it does have manual KVO support using 
> will/didChangeValue(forKey:) then it should be documented as such.
 Use of the ‘dynamic’ keyword enables all manner of runtime hackery which 
 someone may be employing. The trick to automatically add KVO conformance 
 to accessors is probably the most common, but it’s hardly the only one. 
 One also might want to declare things ‘dynamic’ when working with 
 Objective-C frameworks not under one’s control which might assume the 
 ability to do metaprogramming on your classes
>>> 
>>> That is exceedingly rare. I can't even remember the last time I used such a 
>>> thing.
>> 
>> You used such a thing the last time you used KVO. ;-)
> 
> We were talking about metaprogramming other than KVO.

We were talking about libraries and/or frameworks that have the ability to do 
metaprogramming, which when you come down to it is all KVO is. KVO is the most 
popular of these, but keep in mind that all Objective-C code written before 
2014 is assuming that *every* method is *always* going to be dynamically 
dispatched, and as a result may act on those assumptions. For example, consider 
the following contrived example:

import Foundation

class Foo: NSObject {
@objc func sayHello() {
print("Hello World")
}
}

class Bar: NSObject {
@objc func doSomething(with foo: Foo) 
foo.sayHello()
}
}

let foo = Foo()
let bar = Bar()

SomeLegacyObjectiveCAPI().doSomething(with: foo, andSendItBackTo: bar, 
selector: #selector(Bar.doSomething(with:)))

Is this safe? On the surface, it looks like it. However, for all we know, the 
Objective-C API may send us back an NSProxy pretending to be our Foo object, 
rather than the Foo object itself. This is perfectly legal by Objective-C 
conventions, the proxy will look like a Foo due to 

Re: [swift-evolution] Swift Closure still inconsistent -- tuple names need to be in curly brackets, single parameter needs to be in parentheses

2016-12-19 Thread Xiaodi Wu via swift-evolution
This issue about `numbers in` was raised during review of SE-0066; if I
recall, the core team considered and rejected disallowing that syntax in
closures. Since we're minimizing source-breaking changes, the issue is
settled in my view, having been proposed, commented upon, reviewed, and
rejected.
On Mon, Dec 19, 2016 at 15:39 Anton Zhilin via swift-evolution <
swift-evolution@swift.org> wrote:

> 2016-12-17 2:55 GMT+03:00 Vip Malixi via swift-evolution <
> swift-evolution@swift.org>:
>
> var oneParameterAndMultipleReturn: ([Int]) -> (even:[Int], odd:[Int]) = {
> numbers -> ([Int], [Int]) in
> var evenNumberArray = [Int]()
> var oddNumberArray = [Int]()
>
> for number in numbers {
> number % 2 == 0 ? evenNumberArray.append(number) :
> oddNumberArray.append(number)
> }
>
> return (evenNumberArray, oddNumberArray)
> }
>
> The above code is valid, because:
>
>1. Multi-return is just a type of tuple with labeled components.
>2. Labeled tuples and normal tuples are implicitly convertible.
>
> The only way we could make such code invalid is by removing labeled tuples
> altogether. -1 on that.
> This problem mostly refers to code style, and the above variant can be
> more self-documenting in some cases.
>
> Also, again for consistency and clarity, parameters in Closures should
> always be surrounded by parentheses, even single parameters:
>
> var oneParameterAndMultipleReturn: ([Int]) -> ([Int], [Int]) = { (numbers)
> -> (even:[Int], odd:[Int]) in
> var evenNumberArray = [Int]()
> var oddNumberArray = [Int]()
>
> for number in numbers {
> number % 2 == 0 ? evenNumberArray.append(number) :
> oddNumberArray.append(number)
> }
>
> return (evenNumberArray, oddNumberArray)
> }
>
> This should be considered a bug. numbers in or (numbers) in or (numbers)
> -> (...) in, but not numbers -> (...) in, because the latter forms should
> be correct types.
> Whether or not just numbers in should be allowed, is another talk.
> ​
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Derrick Ho via swift-evolution
That is correct Andy. Let-constant can not be assigned a new value after it
gets its initial value.

It is unclear why you are against turning your properties into var's.
Because you are using structs, all properties are copied by value.

struct Person {
  var name: String
}

let andy = Person(name: "Andy")
var brandon = andy; brandon.name = "Brandon"

andy.name // "Andy"
brandon.name // "Brandon"

I believe this accomplishes the same thing you wanted in with(name:)

On Mon, Dec 19, 2016 at 1:26 PM Andy Chou via swift-evolution <
swift-evolution@swift.org> wrote:

Thanks Erica, I wasn't aware of that Swift evolution proposal. If I'm
reading it right, this wouldn't work with structs with let-variables...?
Here's what I get with this example:

struct Person {
let name: String
let address: String
}

@discardableResult
public func with(_ item: T, update:
(inout T) throws -> Void) rethrows -> T {
var this = item
try update()
return this
}

let john = Person(name: "John", address: "1 battery st")
let jane: Person = with(john) { $0.name = "Jane" } // Test.swift:24:41:
Cannot assign to property: 'name' is a 'let' constant

Andy


On Dec 19, 2016, at 11:44 AM, Erica Sadun  wrote:

https://github.com/apple/swift-evolution/pull/346

Be aware that there's a bug that's being worked on:

https://bugs.swift.org/browse/SR-2773

-- E


On Dec 19, 2016, at 12:40 PM, Andy Chou via swift-evolution <
swift-evolution@swift.org> wrote:

Of course. Thanks for pointing out the obvious solution. This preserves the
immutability of the struct and doesn't require O(n^2) code for structs with
large numbers of fields.

I was thinking of a generic solution - perhaps something like a synthetic
initializer that does what your solution does. But that may be overkill
given how relatively easy it is to do this per struct...

On the other hand a generic solution would encourage using immutable
structs. I wasted too much time trying to solve this, I suspect others
would just give up and use var, or even classes.

Andy

On Dec 19, 2016, at 10:43 AM, Nick Keets  wrote:











You are probably asking for a generic solution, but for a specific struct
you can implement it like this:




extension Person {
func with(name: String? = nil, address: String? = nil, phone: String? =
nil) -> Person {
let name = name ?? self.name
let address = address ?? self.address
let phone = phone ?? self.phone
return Person(name: name, address: address, phone: phone)
}
}












On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution <
swift-evolution@swift.org>, wrote:


I like that structs are value types in Swift, this encourages the use of
immutable data. O'Caml has an operator "with" that allows for copying an
existing struct with a change to one field. I looked at Lenses for this
functionality and it seems like a lot to digest for something so simple. I
also tried to implement this using a constructor, or a function, and it was
not obvious how to do so without a lot of code duplication.





What's I'm looking for is something like this (not necessarily with this
syntax):





struct Person {


let name: String


let address: String


let phone: String


}





func f() {


let andy = Person(name: "Andy", address: "1 Battery St., San Francisco,
CA", phone: "1234567")


let chris = andy.with(name: "Chris")


let dave = andy.with(address: "50 Townsend St., San Francisco, CA")


}





I tried to implement a "with" function like this but default arguments
cannot reference properties of self. Same problem trying to do this in a
constructor.





Obviously it's possible to create an entirely new Person specifying the
values from an existing Person, but this is very tedious with structures
with many properties.





Anyone taken a look at this before? Any suggestions?





Andy





___


swift-evolution mailing list


swift-evolution@swift.org


https://lists.swift.org/mailman/listinfo/swift-evolution









___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution



___


swift-evolution mailing list


swift-evolution@swift.org


https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Miguel Bejar via swift-evolution
+1 on this. Scala also has a similar feature (copy constructor) for its
case classes. Right now there's no generic way to do this in Swift, besides
resorting to code generation.

Would this feature have an impact on the ABI and therefore be considered
for Swift 4 part 1?

-Miguel

On Mon, Dec 19, 2016 at 4:29 PM, Andy Chou via swift-evolution <
swift-evolution@swift.org> wrote:

> Thanks Erica, I wasn't aware of that proposal. If I'm reading it right,
> the proposed 'with' function won't work for let-constants in structures,
> e.g.:
>
> struct Person {
> let name: String
> let address: String
> }
>
> @discardableResult
> public func with(_ item: T, update: (inout T) throws -> Void)
> rethrows -> T {
> var this = item
> try update()
> return this
> }
>
> let john = Person(name: "John", address: "1 battery st")
> let jane: Person = with(john) { $0.name = "Jane" }   // Cannot assign to
> property: 'name' is a 'let' constant
>
> Andy
>
> On Dec 19, 2016, at 11:44 AM, Erica Sadun  wrote:
>
> https://github.com/apple/swift-evolution/pull/346
>
> Be aware that there's a bug that's being worked on:
>
> https://bugs.swift.org/browse/SR-2773
>
> -- E
>
>
> On Dec 19, 2016, at 12:40 PM, Andy Chou via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Of course. Thanks for pointing out the obvious solution. This preserves
> the immutability of the struct and doesn't require O(n^2) code for structs
> with large numbers of fields.
>
> I was thinking of a generic solution - perhaps something like a synthetic
> initializer that does what your solution does. But that may be overkill
> given how relatively easy it is to do this per struct...
>
> On the other hand a generic solution would encourage using immutable
> structs. I wasted too much time trying to solve this, I suspect others
> would just give up and use var, or even classes.
>
> Andy
>
> On Dec 19, 2016, at 10:43 AM, Nick Keets  wrote:
>
> You are probably asking for a generic solution, but for a specific struct
> you can implement it like this:
>
> extension Person {
> func with(name: String? = nil, address: String? = nil, phone: String?
> = nil) -> Person {
> let name = name ?? self.name
> let address = address ?? self.address
> let phone = phone ?? self.phone
> return Person(name: name, address: address, phone: phone)
> }
> }
>
>
> On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution <
> swift-evolution@swift.org>, wrote:
>
> I like that structs are value types in Swift, this encourages the use of
> immutable data. O'Caml has an operator "with" that allows for copying an
> existing struct with a change to one field. I looked at Lenses for this
> functionality and it seems like a lot to digest for something so simple. I
> also tried to implement this using a constructor, or a function, and it was
> not obvious how to do so without a lot of code duplication.
>
> What's I'm looking for is something like this (not necessarily with this
> syntax):
>
> struct Person {
> let name: String
> let address: String
> let phone: String
> }
>
> func f() {
> let andy = Person(name: "Andy", address: "1 Battery St., San Francisco,
> CA", phone: "1234567")
> let chris = andy.with(name: "Chris")
> let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
> }
>
> I tried to implement a "with" function like this but default arguments
> cannot reference properties of self. Same problem trying to do this in a
> constructor.
>
> Obviously it's possible to create an entirely new Person specifying the
> values from an existing Person, but this is very tedious with structures
> with many properties.
>
> Anyone taken a look at this before? Any suggestions?
>
> Andy
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Swift Closure still inconsistent -- tuple names need to be in curly brackets, single parameter needs to be in parentheses

2016-12-19 Thread Anton Zhilin via swift-evolution
2016-12-17 2:55 GMT+03:00 Vip Malixi via swift-evolution <
swift-evolution@swift.org>:

var oneParameterAndMultipleReturn: ([Int]) -> (even:[Int], odd:[Int]) = {
> numbers -> ([Int], [Int]) in
> var evenNumberArray = [Int]()
> var oddNumberArray = [Int]()
>
> for number in numbers {
> number % 2 == 0 ? evenNumberArray.append(number) :
> oddNumberArray.append(number)
> }
>
> return (evenNumberArray, oddNumberArray)
> }
>
The above code is valid, because:

   1. Multi-return is just a type of tuple with labeled components.
   2. Labeled tuples and normal tuples are implicitly convertible.

The only way we could make such code invalid is by removing labeled tuples
altogether. -1 on that.
This problem mostly refers to code style, and the above variant can be more
self-documenting in some cases.

Also, again for consistency and clarity, parameters in Closures should
> always be surrounded by parentheses, even single parameters:
>
> var oneParameterAndMultipleReturn: ([Int]) -> ([Int], [Int]) = { (numbers)
> -> (even:[Int], odd:[Int]) in
> var evenNumberArray = [Int]()
> var oddNumberArray = [Int]()
>
> for number in numbers {
> number % 2 == 0 ? evenNumberArray.append(number) :
> oddNumberArray.append(number)
> }
>
> return (evenNumberArray, oddNumberArray)
> }
>
This should be considered a bug. numbers in or (numbers) in or (numbers) ->
(...) in, but not numbers -> (...) in, because the latter forms should be
correct types.
Whether or not just numbers in should be allowed, is another talk.
​
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Andy Chou via swift-evolution
Thanks Erica, I wasn't aware of that proposal. If I'm reading it right, the 
proposed 'with' function won't work for let-constants in structures, e.g.:

struct Person {
let name: String
let address: String
}

@discardableResult
public func with(_ item: T, update: (inout T) throws -> Void) rethrows -> T {
var this = item
try update()
return this
}

let john = Person(name: "John", address: "1 battery st")
let jane: Person = with(john) { $0.name = "Jane" }   // Cannot assign to 
property: 'name' is a 'let' constant

Andy

> On Dec 19, 2016, at 11:44 AM, Erica Sadun  wrote:
> 
> https://github.com/apple/swift-evolution/pull/346 
> 
> 
> Be aware that there's a bug that's being worked on:
> 
> https://bugs.swift.org/browse/SR-2773 
> 
> -- E
> 
> 
>> On Dec 19, 2016, at 12:40 PM, Andy Chou via swift-evolution 
>> > wrote:
>> 
>> Of course. Thanks for pointing out the obvious solution. This preserves the 
>> immutability of the struct and doesn't require O(n^2) code for structs with 
>> large numbers of fields. 
>> 
>> I was thinking of a generic solution - perhaps something like a synthetic 
>> initializer that does what your solution does. But that may be overkill 
>> given how relatively easy it is to do this per struct...
>> 
>> On the other hand a generic solution would encourage using immutable 
>> structs. I wasted too much time trying to solve this, I suspect others would 
>> just give up and use var, or even classes. 
>> 
>> Andy
>> 
>> On Dec 19, 2016, at 10:43 AM, Nick Keets > > wrote:
>> 
>>> You are probably asking for a generic solution, but for a specific struct 
>>> you can implement it like this:
>>> 
>>> extension Person {
>>> func with(name: String? = nil, address: String? = nil, phone: String? = 
>>> nil) -> Person {
>>> let name = name ?? self.name
>>> let address = address ?? self.address
>>> let phone = phone ?? self.phone
>>> return Person(name: name, address: address, phone: phone)
>>> }
>>> }
>>> 
>>> 
>>> On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution 
>>> >, wrote:
 I like that structs are value types in Swift, this encourages the use of 
 immutable data. O'Caml has an operator "with" that allows for copying an 
 existing struct with a change to one field. I looked at Lenses for this 
 functionality and it seems like a lot to digest for something so simple. I 
 also tried to implement this using a constructor, or a function, and it 
 was not obvious how to do so without a lot of code duplication.
 
 What's I'm looking for is something like this (not necessarily with this 
 syntax):
 
 struct Person {
 let name: String
 let address: String
 let phone: String
 }
 
 func f() {
 let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, 
 CA", phone: "1234567")
 let chris = andy.with(name: "Chris")
 let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
 }
 
 I tried to implement a "with" function like this but default arguments 
 cannot reference properties of self. Same problem trying to do this in a 
 constructor.
 
 Obviously it's possible to create an entirely new Person specifying the 
 values from an existing Person, but this is very tedious with structures 
 with many properties.
 
 Anyone taken a look at this before? Any suggestions?
 
 Andy
 
 ___
 swift-evolution mailing list
 swift-evolution@swift.org 
 https://lists.swift.org/mailman/listinfo/swift-evolution 
 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Andy Chou via swift-evolution
Thanks Erica, I wasn't aware of that Swift evolution proposal. If I'm reading 
it right, this wouldn't work with structs with let-variables...?  Here's what I 
get with this example:

struct Person {
let name: String
let address: String
}

@discardableResult
public func with(_ item: T, update: (inout T) throws -> Void) rethrows -> T {
var this = item
try update()
return this
}

let john = Person(name: "John", address: "1 battery st")
let jane: Person = with(john) { $0.name = "Jane" } // Test.swift:24:41: 
Cannot assign to property: 'name' is a 'let' constant

Andy

> On Dec 19, 2016, at 11:44 AM, Erica Sadun  wrote:
> 
> https://github.com/apple/swift-evolution/pull/346 
> 
> 
> Be aware that there's a bug that's being worked on:
> 
> https://bugs.swift.org/browse/SR-2773 
> 
> -- E
> 
> 
>> On Dec 19, 2016, at 12:40 PM, Andy Chou via swift-evolution 
>> > wrote:
>> 
>> Of course. Thanks for pointing out the obvious solution. This preserves the 
>> immutability of the struct and doesn't require O(n^2) code for structs with 
>> large numbers of fields. 
>> 
>> I was thinking of a generic solution - perhaps something like a synthetic 
>> initializer that does what your solution does. But that may be overkill 
>> given how relatively easy it is to do this per struct...
>> 
>> On the other hand a generic solution would encourage using immutable 
>> structs. I wasted too much time trying to solve this, I suspect others would 
>> just give up and use var, or even classes. 
>> 
>> Andy
>> 
>> On Dec 19, 2016, at 10:43 AM, Nick Keets > > wrote:
>> 
>>> You are probably asking for a generic solution, but for a specific struct 
>>> you can implement it like this:
>>> 
>>> extension Person {
>>> func with(name: String? = nil, address: String? = nil, phone: String? = 
>>> nil) -> Person {
>>> let name = name ?? self.name
>>> let address = address ?? self.address
>>> let phone = phone ?? self.phone
>>> return Person(name: name, address: address, phone: phone)
>>> }
>>> }
>>> 
>>> 
>>> On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution 
>>> >, wrote:
 I like that structs are value types in Swift, this encourages the use of 
 immutable data. O'Caml has an operator "with" that allows for copying an 
 existing struct with a change to one field. I looked at Lenses for this 
 functionality and it seems like a lot to digest for something so simple. I 
 also tried to implement this using a constructor, or a function, and it 
 was not obvious how to do so without a lot of code duplication.
 
 What's I'm looking for is something like this (not necessarily with this 
 syntax):
 
 struct Person {
 let name: String
 let address: String
 let phone: String
 }
 
 func f() {
 let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, 
 CA", phone: "1234567")
 let chris = andy.with(name: "Chris")
 let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
 }
 
 I tried to implement a "with" function like this but default arguments 
 cannot reference properties of self. Same problem trying to do this in a 
 constructor.
 
 Obviously it's possible to create an entirely new Person specifying the 
 values from an existing Person, but this is very tedious with structures 
 with many properties.
 
 Anyone taken a look at this before? Any suggestions?
 
 Andy
 
 ___
 swift-evolution mailing list
 swift-evolution@swift.org 
 https://lists.swift.org/mailman/listinfo/swift-evolution 
 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Pattern matching with Arrays

2016-12-19 Thread Anton Zhilin via swift-evolution
2016-12-19 3:09 GMT+03:00 Lucas Neiva via swift-evolution <
swift-evolution@swift.org>:

> case let [first, next...]:
> > case let [first, last]:
>
> The binding should be more like "[let first, let last]" though, to be more
> like the tuple matching. For the above also: "case [let head, let tail...]".
>
Actually, with tuples, case let (first, last) is equivalent to case (let
first, let last), so the “compact” form should be ok with Array pattern
matching.
​
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Nongeneric classes that inherit from generic classes not visible from objc

2016-12-19 Thread Tino Heth via swift-evolution
For me, it wouldn't be important to access those classes from ObjC — but I 
would appreciate being able to use classes with generic ancestors in Xibs.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread David Sweeris via swift-evolution

> On Dec 19, 2016, at 11:55 AM, David Sweeris via swift-evolution 
>  wrote:
> 
> 
>> On Dec 19, 2016, at 11:48 AM, Xiaodi Wu > > wrote:
>> 
>> On Mon, Dec 19, 2016 at 1:44 PM, David Sweeris via swift-evolution 
>> > wrote:
>> 
>>> On Dec 19, 2016, at 11:36 AM, David Sweeris via swift-evolution 
>>> > wrote:
>>> 
>>> 
 On Dec 19, 2016, at 11:21 AM, Erica Sadun via swift-evolution 
 > wrote:
 
 ```swift
 let x = #imageLiteral(resourceName:"nothere.jpg")
 print(x)
 ```
 
 This compiles. It crashes at runtime. I don't see why URLs should be any 
 different.
 
 — E
>>> 
>>> They shouldn’t be. The print function can already handle things that aren’t 
>>> `CustomStringConvertible`:
>>> struct Foo {}
>>> let x = Foo()
>>> Foo.self is CustomStringConvertible //says `false`
>>> print(x) //says `"Foo()\n"`
>>> so, IMHO, that’s a bug.
>> 
>> Oh, hey, wait a second… I didn’t catch the meaning of the resource name, and 
>> thought you meant it was crashing on the print statement. I still think it’s 
>> a bug, because the compiler should be able to check if the resource exists.
>> 
>> I think the point here is that what exists at compile time may not exist at 
>> runtime and vice versa, so while a warning might be elegant, it's not 
>> helpful for the compiler to refuse to proceed on the basis that the image 
>> does not yet exist. At the end of the day, an image literal hardcodes the 
>> path to an image, not the image itself. Whether it ought to is another 
>> kettle of fish.
> 
> Ah, ok, I didn’t realize that image literals weren’t actually created until 
> runtime... In that case, I retract my statement that they shouldn't be any 
> different, because they while they both may be called “literals", they use 
> that word to mean to two quite different things.

I want to elaborate on this a bit… While both of my ideas might (depending on 
what all can be marked @constexpr) allow someone to check whether an URL 
actually points to something at compile-time, in all my examples, I was only 
intending to check that the URL in question was syntactically valid, not 
whether accessing it would result in some sort of “not found” error. You’d 
still have to check at runtime that the server is up & responding, that the 
file is still where you think it is, etc. However, if someone wants to 
expressly make it a syntax error to compile their code while 
“www.my.hardcoded.site.com” is down for maintenance, their internet connection 
is spotty, or whatever... Well… I can’t fathom why that’d be a good idea, but 
IMHO the pros of being able to get compile-time validation of literals far 
out-ways the downside of giving people one more opportunity to write some 
“questionable” code.

Actually, I just thought of one kinda-sorta-not really potentially valid use… 
In a group environment, it could be used to check that a SVC server is up, as a 
guard against trying to work with out-dated code. Personally, I think that’s 
the wrong solution to that particular “problem" (to the extent that it is one), 
but it is a solution (sorta), and I don’t think I can confidently say that it’s 
impossible for something like that to be the right decision for someone else. 
(Yes, it’s a real stretch… I know… the point is that in the amount of time it 
took me to write one paragraph, I went from “this would never be a good idea”, 
to “eh… this would probably never be a good idea”. Given more time to think on 
the possibilities, perhaps someone will think of something really cool and 
useful to do with it.)

- Dave Sweeris___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
The behavior is not altogether clear to me either. Since XCode does show a
preview of images, it's fair to think that there's some sort of
compile-time validation going on.

I would not be opposed to image and file literals changing their behavior
so that when a user drags a file into the IDE the file contents are what
are embedded via a data URL, rather than a file path. I do know that in a
Playground, when you choose a file for a file literal, an alias is made to
that file stored in a different folder for Playground resources, and it's
that alias which is referenced in the resulting URL. This seems brittle to
me.

On Mon, Dec 19, 2016 at 13:55 David Sweeris  wrote:

>
> On Dec 19, 2016, at 11:48 AM, Xiaodi Wu  wrote:
>
> On Mon, Dec 19, 2016 at 1:44 PM, David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 19, 2016, at 11:36 AM, David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 19, 2016, at 11:21 AM, Erica Sadun via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> ```swift
> let x = #imageLiteral(resourceName:"nothere.jpg")
> print(x)
> ```
>
> This compiles. It crashes at runtime. I don't see why URLs should be any
> different.
>
> — E
>
>
> They shouldn’t be. The print function can already handle things that
> aren’t `CustomStringConvertible`:
>
> struct Foo {}
> let x = Foo()
> Foo.self is CustomStringConvertible //says `false`
> print(x) //says `"Foo()\n"`
>
> so, IMHO, that’s a bug.
>
>
> Oh, hey, wait a second… I didn’t catch the meaning of the resource name,
> and thought you meant it was crashing on the print statement. I still think
> it’s a bug, because the compiler should be able to check if the resource
> exists.
>
>
> I think the point here is that what exists at compile time may not exist
> at runtime and vice versa, so while a warning might be elegant, it's not
> helpful for the compiler to refuse to proceed on the basis that the image
> does not yet exist. At the end of the day, an image literal hardcodes the
> path to an image, not the image itself. Whether it ought to is another
> kettle of fish.
>
>
> Ah, ok, I didn’t realize that image literals weren’t actually created
> until runtime... In that case, I retract my statement that they shouldn't
> be any different, because they while they both may be called “literals",
> they use that word to mean to two quite different things.
>
> - Dave Sweeris
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Changing NSObject dispatch behavior

2016-12-19 Thread Kevin Ballard via swift-evolution
On Fri, Dec 16, 2016, at 06:30 AM, Charles Srstka wrote:
>> On Dec 16, 2016, at 12:36 AM, Kevin Ballard  wrote:
>> 

>> On Thu, Dec 15, 2016, at 03:01 PM, Charles Srstka wrote:
 On Dec 15, 2016, at 4:33 PM, Kevin Ballard  wrote:
 

 The problem with that code isn't that `dynamic` doesn't work for
 computed properties. It does; if you mutate the `foo` property,
 you'll get the KVO notifications. The problem is you have one
 property that depends on another and you didn't set up the KVO
 machinery properly using automaticallyNotifiesObservers(forKey:) or
 automaticallyNotifiesObserversOf() (incidentally in Swift you
 can write the latter as a `static let`, since that becomes a class
 method in Obj-C).
>>> 

>>> You’ll only get the notifications if you mutate ‘foo’ directly.
>>> This, however, is fairly useless, because if you are watching ‘foo’,
>>> you want to be notified every time the value changes, not just when
>>> someone hits one particular accessor. Code relying on observation of
>>> ‘foo’ in the example I provided would be prone to breaking in
>>> mysterious and possibly horrible ways.
>> 

>> No, if you implement keyPathsForValuesAffecting()  then you get
>> "foo" KVO notifications when "bar" is mutated.  That's the whole
>> point of that method, and this is exactly what you have to do in Obj-
>> C as well.
> 

> Right… the sentence I was quoting was talking about code which uses
> ‘dynamic’ but *doesn’t* use keyPathsForValuesAffecting. You’ll
> get notifications if someone calls that one particular accessor, but
> otherwise you won’t.


You can always write buggy code. If you're using `dynamic` for KVO
purposes, then not implementing keyPathsForValuesAffecting in this
case is strictly a bug. If you're using `dynamic` for something other
than KVO, and your property won't end up supporting KVO properly by
default, then you should document it as such, given that the natural
assumption for a `dynamic` property is that it supports KVO.


 So yes, `dynamic` by itself doesn't mean that the property supports
 KVO. But there are very few reasons to use `dynamic` outside of
 supporting KVO, so it's a pretty good signal that the property does
 support it. And conversely, not having `dynamic` doesn't mean that
 it doesn't support KVO, though if it does have manual KVO support
 using will/didChangeValue(forKey:) then it should be documented as
 such.
>>> Use of the ‘dynamic’ keyword enables all manner of runtime hackery
>>> which someone may be employing. The trick to automatically add KVO
>>> conformance to accessors is probably the most common, but it’s
>>> hardly the only one. One also might want to declare things ‘dynamic’
>>> when working with Objective-C frameworks not under one’s control
>>> which might assume the ability to do metaprogramming on your classes
>> 

>> That is exceedingly rare. I can't even remember the last time I used
>> such a thing.
> 

> You used such a thing the last time you used KVO. ;-)



We were talking about metaprogramming other than KVO.



>>> I know it’s commonplace to use ‘dynamic’ all over the place wherever
>>> Core Data is involved.
>> 

>> It is? Why? Maybe you're confusing this with Obj-C's @dynamic
>> keyword, which is completely unrelated to Swift's `dynamic`. When
>> writing Swift NSManagedObject subclasses, you use the @NSManaged
>> property attribute, not the `dynamic` keyword (@NSManaged does
>> effectively the same thing that Obj-C's @dynamic, except it's
>> reserved for integration with CoreData instead of being as generic as
>> Obj-C's @dynamic is).
> 

> @NSManaged implies dynamic, though. Core Data is entirely built on the
> dynamic runtime, and is using it pretty much everywhere.


@NSManaged could easily be implemented by codegenning static-dispatch
methods that invoke the primitive accessors and will/didChange KVO
broadcasts. Presumably it doesn't (presumably it does literally the same
thing @dynamic does in Obj-C, which is that it makes the assumption that
the methods exist at runtime even though they're unknown at compile-
time), but there's nothing about @NSManaged that requires it to always
use dynamic dispatch. Core Data leverages the dynamic runtime for method
generation, but it doesn't actually require it (you can completely
ignore dynamicism and implement your properties in terms of
primitiveValue(forKey:) and setPrimitiveValue(_:forKey:), though the 
dynamically-
synthesized primitive accessors are supposed to be more efficient).


>>> Long story short, ‘dynamic’ does not guarantee KVO conformance in
>>> any way, shape, or form.
>> 

>> And declaring that your property returns a String doesn't guarantee
>> that it actually does either. You can always write broken code. But
>> `dynamic` is required for automatic KVO conformance, and it's
>> extremely rare to have a reason to use `dynamic` outside of KVO, so
>> it's a really really strong signal that 

Re: [swift-evolution] URL Literals

2016-12-19 Thread David Sweeris via swift-evolution

> On Dec 19, 2016, at 11:48 AM, Xiaodi Wu  wrote:
> 
> On Mon, Dec 19, 2016 at 1:44 PM, David Sweeris via swift-evolution 
> > wrote:
> 
>> On Dec 19, 2016, at 11:36 AM, David Sweeris via swift-evolution 
>> > wrote:
>> 
>> 
>>> On Dec 19, 2016, at 11:21 AM, Erica Sadun via swift-evolution 
>>> > wrote:
>>> 
>>> ```swift
>>> let x = #imageLiteral(resourceName:"nothere.jpg")
>>> print(x)
>>> ```
>>> 
>>> This compiles. It crashes at runtime. I don't see why URLs should be any 
>>> different.
>>> 
>>> — E
>> 
>> They shouldn’t be. The print function can already handle things that aren’t 
>> `CustomStringConvertible`:
>> struct Foo {}
>> let x = Foo()
>> Foo.self is CustomStringConvertible //says `false`
>> print(x) //says `"Foo()\n"`
>> so, IMHO, that’s a bug.
> 
> Oh, hey, wait a second… I didn’t catch the meaning of the resource name, and 
> thought you meant it was crashing on the print statement. I still think it’s 
> a bug, because the compiler should be able to check if the resource exists.
> 
> I think the point here is that what exists at compile time may not exist at 
> runtime and vice versa, so while a warning might be elegant, it's not helpful 
> for the compiler to refuse to proceed on the basis that the image does not 
> yet exist. At the end of the day, an image literal hardcodes the path to an 
> image, not the image itself. Whether it ought to is another kettle of fish.

Ah, ok, I didn’t realize that image literals weren’t actually created until 
runtime... In that case, I retract my statement that they shouldn't be any 
different, because they while they both may be called “literals", they use that 
word to mean to two quite different things.

- Dave Sweeris

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
On Mon, Dec 19, 2016 at 1:44 PM, David Sweeris via swift-evolution <
swift-evolution@swift.org> wrote:

>
> On Dec 19, 2016, at 11:36 AM, David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 19, 2016, at 11:21 AM, Erica Sadun via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> ```swift
> let x = #imageLiteral(resourceName:"nothere.jpg")
> print(x)
> ```
>
> This compiles. It crashes at runtime. I don't see why URLs should be any
> different.
>
> — E
>
>
> They shouldn’t be. The print function can already handle things that
> aren’t `CustomStringConvertible`:
>
> struct Foo {}
> let x = Foo()
> Foo.self is CustomStringConvertible //says `false`
> print(x) //says `"Foo()\n"`
>
> so, IMHO, that’s a bug.
>
>
> Oh, hey, wait a second… I didn’t catch the meaning of the resource name,
> and thought you meant it was crashing on the print statement. I still think
> it’s a bug, because the compiler should be able to check if the resource
> exists.
>

I think the point here is that what exists at compile time may not exist at
runtime and vice versa, so while a warning might be elegant, it's not
helpful for the compiler to refuse to proceed on the basis that the image
does not yet exist. At the end of the day, an image literal hardcodes the
path to an image, not the image itself. Whether it ought to is another
kettle of fish.


> - Dave Sweeris
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread David Sweeris via swift-evolution

> On Dec 19, 2016, at 11:36 AM, David Sweeris via swift-evolution 
>  wrote:
> 
> 
>> On Dec 19, 2016, at 11:21 AM, Erica Sadun via swift-evolution 
>> > wrote:
>> 
>> ```swift
>> let x = #imageLiteral(resourceName:"nothere.jpg")
>> print(x)
>> ```
>> 
>> This compiles. It crashes at runtime. I don't see why URLs should be any 
>> different.
>> 
>> — E
> 
> They shouldn’t be. The print function can already handle things that aren’t 
> `CustomStringConvertible`:
> struct Foo {}
> let x = Foo()
> Foo.self is CustomStringConvertible //says `false`
> print(x) //says `"Foo()\n"`
> so, IMHO, that’s a bug.

Oh, hey, wait a second… I didn’t catch the meaning of the resource name, and 
thought you meant it was crashing on the print statement. I still think it’s a 
bug, because the compiler should be able to check if the resource exists.

- Dave Sweeris___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
On Mon, Dec 19, 2016 at 1:40 PM, Xiaodi Wu  wrote:

> On Mon, Dec 19, 2016 at 1:18 PM, Tony Allevato 
> wrote:
>
>> +1 to the sentiment in your last paragraph.
>>
>> In general, I'm not a very big fan of the #foo(...) syntax for literals
>> and I think using that as the starting point for discussion biases us
>> towards those when more general and powerful alternatives could exist. That
>> syntax exists for Playground support and I'd hate to see it proliferate
>> into non-playground sources. Furthermore, if the user could write a
>> compile-time-validating initializer for `URL("http://foo.com/bar;)` (or
>> `let url: URL = "http://foo.com/bar"`), then that expression becomes
>> just as much a "literal" as something like `#url("http://foo.com/bar;)`.
>> There's no functional difference between the two: both are sequences of
>> tokens that the compiler can evaluate statically. The benefit is that the
>> end user doesn't have to worry about the distinction; the compiler picks
>> the appropriate evaluation automatically depending on whether the
>> initializer argument is statically known or not.
>>
>
> +1 to this. If we could mark an initializer for URL as a constexpr that
> takes a string literal, then conformance to ExpressibleByStringLiteral
> would make `let foo = URL("http://example.com;)`
>

Rather, I meant `let foo: URL = "http://example.com"`.


> work exactly as desired at compile time, and this is IMO the most elegant
> solution.
>
> Taking this a step further, if we can get constexpr-like validation for
>> initializers like this, then I wonder if the #foo literal syntax needs to
>> exist at all, and I'd propose that we abandon it and just let the
>> playground UI and other IDEs transform things like `UIColor(red: 0.5,
>> green: 0.5, blue: 0.5)` into a swatch when it sees them if they can be
>> evaluated at compile-time. What you lose is, as Erica mentioned earlier,
>> the fact that `#colorLiteral(...)` is untyped and can be turned into
>> multiple color types, but the value already has to be assigned to a
>> concrete type eventually anyway.
>>
>> Am I missing any use cases for things like #colorLiteral that doing this
>> would make difficult or impossible?
>>
>>
>> On Mon, Dec 19, 2016 at 10:53 AM David Sweeris via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>>
>>> On Dec 19, 2016, at 1:26 AM, Xiaodi Wu  wrote:
>>>
>>> URLs are unlikely to be something that can be validated by regex. See,
>>> for instance, this discussion: >> url-parsing-in-webkit/>. The full spec is here: <
>>> https://url.spec.whatwg.org>. If Swift were to implement parsing of
>>> URLs at the level of the compiler or core library, I'd expect it to be the
>>> full spec, as we do with Unicode.
>>>
>>>
>>> On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution
>>>  wrote:
>>>
>>> Howdy,
>>> Yes, I was also intrigued by the “Regex” validation mentioned in another
>>> post.  It could offer a convenient way to get some literals support in
>>> without the headaches associated with the constexpr C++ approach.
>>> I’m curious, though, how many types can we image in can be validated by
>>> this method?  If it really is just URL’s, then I’d actually lean towards
>>> making this a compiler magic feature.
>>>
>>> Someone else mentioned fetching the URL’s for a preview.  Given that we
>>> might be coding “deletes” in URL’s (yes, I recently met a backend developer
>>> who coded a delete as a GET), I really highly suggest we not ping people’s
>>> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO,
>>> verifying that a service is active isn’t really the Swift compiler’s job.
>>> It might happen as part of coordinated run-time tests, which sometimes have
>>> to be balanced to keep test data correct, something the IDE wouldn’t know
>>> how to enforce correctly.
>>> -Ben
>>>
>>> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>>
>>> On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> I'd love a fleshed out elegant example for URL that shows what a
>>> complete implementation of that special init method would look like.
>>>
>>>
>>> Sorry this took so long… the weekend kinda got away from me.
>>>
>>> Anyway, I was thinking something like this (which has been very
>>> simplified on account of my regexing being sub-sketchy, and me not knowing
>>> exactly what’s valid in an URL anyway):
>>>
>>> #literalpatterns += (name: “URLLiteralType”, components: (name: url,
>>> type: StringLiteralType, pattern: “(http|https)://(www.)?[a-z|A-Z|0-9]+
>>> .(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
>>> protocol: ExpressibleByURLLiteral)
>>>
>>> This would let the compiler know pretty much everything it needs to
>>> know… that the “new” type is called 

Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
On Mon, Dec 19, 2016 at 1:18 PM, Tony Allevato  wrote:

> +1 to the sentiment in your last paragraph.
>
> In general, I'm not a very big fan of the #foo(...) syntax for literals
> and I think using that as the starting point for discussion biases us
> towards those when more general and powerful alternatives could exist. That
> syntax exists for Playground support and I'd hate to see it proliferate
> into non-playground sources. Furthermore, if the user could write a
> compile-time-validating initializer for `URL("http://foo.com/bar;)` (or
> `let url: URL = "http://foo.com/bar"`), then that expression becomes just
> as much a "literal" as something like `#url("http://foo.com/bar;)`.
> There's no functional difference between the two: both are sequences of
> tokens that the compiler can evaluate statically. The benefit is that the
> end user doesn't have to worry about the distinction; the compiler picks
> the appropriate evaluation automatically depending on whether the
> initializer argument is statically known or not.
>

+1 to this. If we could mark an initializer for URL as a constexpr that
takes a string literal, then conformance to ExpressibleByStringLiteral
would make `let foo = URL("http://example.com;)` work exactly as desired at
compile time, and this is IMO the most elegant solution.

Taking this a step further, if we can get constexpr-like validation for
> initializers like this, then I wonder if the #foo literal syntax needs to
> exist at all, and I'd propose that we abandon it and just let the
> playground UI and other IDEs transform things like `UIColor(red: 0.5,
> green: 0.5, blue: 0.5)` into a swatch when it sees them if they can be
> evaluated at compile-time. What you lose is, as Erica mentioned earlier,
> the fact that `#colorLiteral(...)` is untyped and can be turned into
> multiple color types, but the value already has to be assigned to a
> concrete type eventually anyway.
>
> Am I missing any use cases for things like #colorLiteral that doing this
> would make difficult or impossible?
>
>
> On Mon, Dec 19, 2016 at 10:53 AM David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>>
>> On Dec 19, 2016, at 1:26 AM, Xiaodi Wu  wrote:
>>
>> URLs are unlikely to be something that can be validated by regex. See,
>> for instance, this discussion: > url-parsing-in-webkit/>. The full spec is here: <
>> https://url.spec.whatwg.org>. If Swift were to implement parsing of URLs
>> at the level of the compiler or core library, I'd expect it to be the full
>> spec, as we do with Unicode.
>>
>>
>> On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Howdy,
>> Yes, I was also intrigued by the “Regex” validation mentioned in another
>> post.  It could offer a convenient way to get some literals support in
>> without the headaches associated with the constexpr C++ approach.
>> I’m curious, though, how many types can we image in can be validated by
>> this method?  If it really is just URL’s, then I’d actually lean towards
>> making this a compiler magic feature.
>>
>> Someone else mentioned fetching the URL’s for a preview.  Given that we
>> might be coding “deletes” in URL’s (yes, I recently met a backend developer
>> who coded a delete as a GET), I really highly suggest we not ping people’s
>> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO,
>> verifying that a service is active isn’t really the Swift compiler’s job.
>> It might happen as part of coordinated run-time tests, which sometimes have
>> to be balanced to keep test data correct, something the IDE wouldn’t know
>> how to enforce correctly.
>> -Ben
>>
>> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>
>> On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> I'd love a fleshed out elegant example for URL that shows what a complete
>> implementation of that special init method would look like.
>>
>>
>> Sorry this took so long… the weekend kinda got away from me.
>>
>> Anyway, I was thinking something like this (which has been very
>> simplified on account of my regexing being sub-sketchy, and me not knowing
>> exactly what’s valid in an URL anyway):
>>
>> #literalpatterns += (name: “URLLiteralType”, components: (name: url,
>> type: StringLiteralType, pattern: “(http|https)://(www.)?[a-z|A-Z|0-9]+
>> .(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
>> protocol: ExpressibleByURLLiteral)
>>
>> This would let the compiler know pretty much everything it needs to know…
>> that the “new” type is called “URLLiteralType", that it starts out life as
>> young StringLiteralType with a bright future in the computer industry, that
>> in order to succeed it has to match a given pattern, and what protocol a
>> type has to conform to in order to use 

Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Andy Chou via swift-evolution
Of course. Thanks for pointing out the obvious solution. This preserves the 
immutability of the struct and doesn't require O(n^2) code for structs with 
large numbers of fields. 

I was thinking of a generic solution - perhaps something like a synthetic 
initializer that does what your solution does. But that may be overkill given 
how relatively easy it is to do this per struct...

On the other hand a generic solution would encourage using immutable structs. I 
wasted too much time trying to solve this, I suspect others would just give up 
and use var, or even classes. 

Andy

> On Dec 19, 2016, at 10:43 AM, Nick Keets  wrote:
> 
> You are probably asking for a generic solution, but for a specific struct you 
> can implement it like this:
> 
> extension Person {
> func with(name: String? = nil, address: String? = nil, phone: String? = 
> nil) -> Person {
> let name = name ?? self.name
> let address = address ?? self.address
> let phone = phone ?? self.phone
> return Person(name: name, address: address, phone: phone)
> }
> }
> 
> 
>> On 19 Dec 2016, 20:28 +0200, Andy Chou via swift-evolution 
>> , wrote:
>> I like that structs are value types in Swift, this encourages the use of 
>> immutable data. O'Caml has an operator "with" that allows for copying an 
>> existing struct with a change to one field. I looked at Lenses for this 
>> functionality and it seems like a lot to digest for something so simple. I 
>> also tried to implement this using a constructor, or a function, and it was 
>> not obvious how to do so without a lot of code duplication.
>> 
>> What's I'm looking for is something like this (not necessarily with this 
>> syntax):
>> 
>> struct Person {
>> let name: String
>> let address: String
>> let phone: String
>> }
>> 
>> func f() {
>> let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, CA", 
>> phone: "1234567")
>> let chris = andy.with(name: "Chris")
>> let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
>> }
>> 
>> I tried to implement a "with" function like this but default arguments 
>> cannot reference properties of self. Same problem trying to do this in a 
>> constructor.
>> 
>> Obviously it's possible to create an entirely new Person specifying the 
>> values from an existing Person, but this is very tedious with structures 
>> with many properties.
>> 
>> Anyone taken a look at this before? Any suggestions?
>> 
>> Andy
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread David Sweeris via swift-evolution

> On Dec 19, 2016, at 11:21 AM, Erica Sadun via swift-evolution 
>  wrote:
> 
> ```swift
> let x = #imageLiteral(resourceName:"nothere.jpg")
> print(x)
> ```
> 
> This compiles. It crashes at runtime. I don't see why URLs should be any 
> different.
> 
> — E

They shouldn’t be. The print function can already handle things that aren’t 
`CustomStringConvertible`:
struct Foo {}
let x = Foo()
Foo.self is CustomStringConvertible //says `false`
print(x) //says `"Foo()\n"`
so, IMHO, that’s a bug.

- Dave Sweeris___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Erica Sadun via swift-evolution

> On Dec 19, 2016, at 12:18 PM, Tony Allevato via swift-evolution 
>  wrote:
> 
> +1 to the sentiment in your last paragraph.
> 
> In general, I'm not a very big fan of the #foo(...) syntax for literals and I 
> think using that as the starting point for discussion biases us towards those 
> when more general and powerful alternatives could exist. That syntax exists 
> for Playground support and I'd hate to see it proliferate into non-playground 
> sources.

I like the syntax. I'd like to see more of the syntax. Problem is they stand 
out in their current definition.

I'm not sure where these platform-independent concepts should go but I don't 
believe it should be in the standard library or Foundation. 

> Taking this a step further, if we can get constexpr-like validation for 
> initializers like this, then I wonder if the #foo literal syntax needs to 
> exist at all, and I'd propose that we abandon it and just let the playground 
> UI and other IDEs transform things like `UIColor(red: 0.5, green: 0.5, blue: 
> 0.5)` into a swatch when it sees them if they can be evaluated at 
> compile-time. What you lose is, as Erica mentioned earlier, the fact that 
> `#colorLiteral(...)` is untyped and can be turned into multiple color types, 
> but the value already has to be assigned to a concrete type eventually anyway.

If you don't provide an inferable type, it errors with "Could not infer type of 
color literal".

> Am I missing any use cases for things like #colorLiteral that doing this 
> would make difficult or impossible?

There are issues with wide color vs device color for example. I've assumed that 
device is presumed. You can create

#colorLiteral(red: 5.1764705926, green: 0.01176470611, blue: -0.5607843399, 
alpha: 1000)

and this produces with Cocoa and tvOS UIKit:

NSCustomColorSpace sRGB IEC61966-2.1 colorspace 5.17647 0.0117647 -0.560784 1000
UIExtendedSRGBColorSpace 5.17647 0.0117647 -0.560784 1

-- E

> 
> 
> On Mon, Dec 19, 2016 at 10:53 AM David Sweeris via swift-evolution 
> > wrote:
> 
>> On Dec 19, 2016, at 1:26 AM, Xiaodi Wu > > wrote:
>> 
>> URLs are unlikely to be something that can be validated by regex. See, for 
>> instance, this discussion: 
>> > >. The full spec is 
>> here: >. If Swift 
>> were to implement parsing of URLs at the level of the compiler or core 
>> library, I'd expect it to be the full spec, as we do with Unicode.
>> 
>> 
>> On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution 
>> > wrote:
>> Howdy,
>>  Yes, I was also intrigued by the “Regex” validation mentioned in 
>> another post.  It could offer a convenient way to get some literals support 
>> in without the headaches associated with the constexpr C++ approach.
>>  I’m curious, though, how many types can we image in can be validated by 
>> this method?  If it really is just URL’s, then I’d actually lean towards 
>> making this a compiler magic feature.
>> 
>>  Someone else mentioned fetching the URL’s for a preview.  Given that we 
>> might be coding “deletes” in URL’s (yes, I recently met a backend developer 
>> who coded a delete as a GET), I really highly suggest we not ping people’s 
>> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO, 
>> verifying that a service is active isn’t really the Swift compiler’s job.  
>> It might happen as part of coordinated run-time tests, which sometimes have 
>> to be balanced to keep test data correct, something the IDE wouldn’t know 
>> how to enforce correctly.
>> -Ben
>> 
>>> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution 
>>> > wrote:
>>> 
>>> 
 On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution 
 > wrote:
 
 I'd love a fleshed out elegant example for URL that shows what a complete 
 implementation of that special init method would look like. 
>>> 
>>> Sorry this took so long… the weekend kinda got away from me.
>>> 
>>> Anyway, I was thinking something like this (which has been very simplified 
>>> on account of my regexing being sub-sketchy, and me not knowing exactly 
>>> what’s valid in an URL anyway):
>>> #literalpatterns += (name: “URLLiteralType”, components: (name: url, type: 
>>> StringLiteralType, pattern: 
>>> “(http|https)://(www.)?[a-z|A-Z|0-9]+.(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
>>>  protocol: ExpressibleByURLLiteral)
>>> This would let the compiler know pretty much everything it needs to know… 
>>> that the “new” type is called 

Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Rien via swift-evolution
A little more work, but I like this pattern.

struct Person {

let name: String
let address: String
let phone: String

func name(_ n: String) -> Person {
return Person(name: n, address: self.address, phone: self.phone)
}

func address(_ a: String) -> Person {
return Person(name: self.name, address: a, phone: self.phone)
}

func phone(_ p: String) -> Person {
return Person(name: self.name, address: self.address, phone: p)
}
}

let p1 = Person(name: "Andrew", address: "Milkyway", phone: "031234")

let p2 = p1.name("Bart")

let p3 = p2.name("Jack").address("Earth”)

Regards,
Rien

Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Swiftrien
Project: http://swiftfire.nl




> On 18 Dec 2016, at 02:40, Andy Chou via swift-evolution 
>  wrote:
> 
> I like that structs are value types in Swift, this encourages the use of 
> immutable data. O'Caml has an operator "with" that allows for copying an 
> existing struct with a change to one field. I looked at Lenses for this 
> functionality and it seems like a lot to digest for something so simple. I 
> also tried to implement this using a constructor, or a function, and it was 
> not obvious how to do so without a lot of code duplication.
> 
> What's I'm looking for is something like this (not necessarily with this 
> syntax):
> 
> struct Person {
>let name: String
>let address: String
>let phone: String
> }
> 
> func f() {
>let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, 
> CA", phone: "1234567")
>let chris = andy.with(name: "Chris")
>let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
> }
> 
> I tried to implement a "with" function like this but default arguments cannot 
> reference properties of self. Same problem trying to do this in a constructor.
> 
> Obviously it's possible to create an entirely new Person specifying the 
> values from an existing Person, but this is very tedious with structures with 
> many properties.
> 
> Anyone taken a look at this before? Any suggestions?
> 
> Andy
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Erica Sadun via swift-evolution
```swift
let x = #imageLiteral(resourceName:"nothere.jpg")
print(x)
```

This compiles. It crashes at runtime. I don't see why URLs should be any 
different.

-- E


> On Dec 19, 2016, at 11:53 AM, David Sweeris via swift-evolution 
>  wrote:
> 
>> 
>> On Dec 19, 2016, at 1:26 AM, Xiaodi Wu > > wrote:
>> 
>> URLs are unlikely to be something that can be validated by regex. See, for 
>> instance, this discussion: 
>> > >. The full spec is 
>> here: >. If Swift 
>> were to implement parsing of URLs at the level of the compiler or core 
>> library, I'd expect it to be the full spec, as we do with Unicode.
>> 
>> 
>> On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution 
>> > wrote:
>> Howdy,
>>  Yes, I was also intrigued by the “Regex” validation mentioned in 
>> another post.  It could offer a convenient way to get some literals support 
>> in without the headaches associated with the constexpr C++ approach.
>>  I’m curious, though, how many types can we image in can be validated by 
>> this method?  If it really is just URL’s, then I’d actually lean towards 
>> making this a compiler magic feature.
>> 
>>  Someone else mentioned fetching the URL’s for a preview.  Given that we 
>> might be coding “deletes” in URL’s (yes, I recently met a backend developer 
>> who coded a delete as a GET), I really highly suggest we not ping people’s 
>> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO, 
>> verifying that a service is active isn’t really the Swift compiler’s job.  
>> It might happen as part of coordinated run-time tests, which sometimes have 
>> to be balanced to keep test data correct, something the IDE wouldn’t know 
>> how to enforce correctly.
>> -Ben
>> 
>>> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution 
>>> > wrote:
>>> 
>>> 
 On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution 
 > wrote:
 
 I'd love a fleshed out elegant example for URL that shows what a complete 
 implementation of that special init method would look like. 
>>> 
>>> Sorry this took so long… the weekend kinda got away from me.
>>> 
>>> Anyway, I was thinking something like this (which has been very simplified 
>>> on account of my regexing being sub-sketchy, and me not knowing exactly 
>>> what’s valid in an URL anyway):
>>> #literalpatterns += (name: “URLLiteralType”, components: (name: url, type: 
>>> StringLiteralType, pattern: 
>>> “(http|https)://(www.)?[a-z|A-Z|0-9]+.(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
>>>  protocol: ExpressibleByURLLiteral)
>>> This would let the compiler know pretty much everything it needs to know… 
>>> that the “new” type is called “URLLiteralType", that it starts out life as 
>>> young StringLiteralType with a bright future in the computer industry, that 
>>> in order to succeed it has to match a given pattern, and what protocol a 
>>> type has to conform to in order to use an URLLiteral. In practice, the 
>>> compiler would synthesize a struct containing the specified members and 
>>> validate the literal with the specified pattern before making an “instance” 
>>> of it (since we’re talking about literals and compile-time code here, I’m 
>>> pretty sure that “instance" the wrong terminology… pardon my ignorance)
>>> struct URLLiteralType: {
>>> let url: StringLiteralType
>>> }
>>> A tuple would be better, IMHO, but according to the playground, 
>>> single-element tuples can’t have element labels. As for the implementation 
>>> of the init function:
>>> init(urlLiteral value: URLLiteralType) {
>>> let urlString = value.url
>>> //Do whatever URL is doing now, except there’s no need to check for 
>>> errors since the compiler pre-validated it for us
>>> }
>>> 
>>> If it’d be more useful, the pattern could be split into multiple pieces:
>>> #literalpatterns += (name: “URLLiteralType”,
>>>  components: ((name: “`protocol`", type: 
>>> StringLiteralType, pattern: “(http|https)”),
>>>   (name: _,type: 
>>> StringLiteralType, pattern: “://”),
>>>   (name: “domain", type: 
>>> StringLiteralType, pattern: “(www.)?[a-z|A-Z|0-9]+.(com|org|net)”),
>>>   (name: “path”,   type: 
>>> StringLiteralType, pattern: 
>>> "(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”))
>>>  protocol: ExpressibleByURLLiteral)
>>> This would result in URLLiteralType looking like this:
>>> struct URLLiteralType: {
>>>  

Re: [swift-evolution] URL Literals

2016-12-19 Thread Tony Allevato via swift-evolution
+1 to the sentiment in your last paragraph.

In general, I'm not a very big fan of the #foo(...) syntax for literals and
I think using that as the starting point for discussion biases us towards
those when more general and powerful alternatives could exist. That syntax
exists for Playground support and I'd hate to see it proliferate into
non-playground sources. Furthermore, if the user could write a
compile-time-validating initializer for `URL("http://foo.com/bar;)` (or
`let url: URL = "http://foo.com/bar"`), then that expression becomes just
as much a "literal" as something like `#url("http://foo.com/bar;)`. There's
no functional difference between the two: both are sequences of tokens that
the compiler can evaluate statically. The benefit is that the end user
doesn't have to worry about the distinction; the compiler picks the
appropriate evaluation automatically depending on whether the initializer
argument is statically known or not.

Taking this a step further, if we can get constexpr-like validation for
initializers like this, then I wonder if the #foo literal syntax needs to
exist at all, and I'd propose that we abandon it and just let the
playground UI and other IDEs transform things like `UIColor(red: 0.5,
green: 0.5, blue: 0.5)` into a swatch when it sees them if they can be
evaluated at compile-time. What you lose is, as Erica mentioned earlier,
the fact that `#colorLiteral(...)` is untyped and can be turned into
multiple color types, but the value already has to be assigned to a
concrete type eventually anyway.

Am I missing any use cases for things like #colorLiteral that doing this
would make difficult or impossible?


On Mon, Dec 19, 2016 at 10:53 AM David Sweeris via swift-evolution <
swift-evolution@swift.org> wrote:

>
> On Dec 19, 2016, at 1:26 AM, Xiaodi Wu  wrote:
>
> URLs are unlikely to be something that can be validated by regex. See, for
> instance, this discussion: <
> https://webkit.org/blog/7086/url-parsing-in-webkit/>. The full spec is
> here: . If Swift were to implement parsing
> of URLs at the level of the compiler or core library, I'd expect it to be
> the full spec, as we do with Unicode.
>
>
> On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Howdy,
> Yes, I was also intrigued by the “Regex” validation mentioned in another
> post.  It could offer a convenient way to get some literals support in
> without the headaches associated with the constexpr C++ approach.
> I’m curious, though, how many types can we image in can be validated by
> this method?  If it really is just URL’s, then I’d actually lean towards
> making this a compiler magic feature.
>
> Someone else mentioned fetching the URL’s for a preview.  Given that we
> might be coding “deletes” in URL’s (yes, I recently met a backend developer
> who coded a delete as a GET), I really highly suggest we not ping people’s
> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO,
> verifying that a service is active isn’t really the Swift compiler’s job.
> It might happen as part of coordinated run-time tests, which sometimes have
> to be balanced to keep test data correct, something the IDE wouldn’t know
> how to enforce correctly.
> -Ben
>
> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I'd love a fleshed out elegant example for URL that shows what a complete
> implementation of that special init method would look like.
>
>
> Sorry this took so long… the weekend kinda got away from me.
>
> Anyway, I was thinking something like this (which has been very simplified
> on account of my regexing being sub-sketchy, and me not knowing exactly
> what’s valid in an URL anyway):
>
> #literalpatterns += (name: “URLLiteralType”, components: (name: url,
> type: StringLiteralType, pattern: “(http|https)://(www.)?[a-z|A-Z|0-9]+
> .(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
> protocol: ExpressibleByURLLiteral)
>
> This would let the compiler know pretty much everything it needs to know…
> that the “new” type is called “URLLiteralType", that it starts out life as
> young StringLiteralType with a bright future in the computer industry, that
> in order to succeed it has to match a given pattern, and what protocol a
> type has to conform to in order to use an URLLiteral. In practice, the
> compiler would synthesize a struct containing the specified members and
> validate the literal with the specified pattern before making an “instance”
> of it (since we’re talking about literals and compile-time code here, I’m
> pretty sure that “instance" the wrong terminology… pardon my ignorance)
>
> struct URLLiteralType: {
> let url: StringLiteralType
> }
>
> A tuple would be better, IMHO, but according to the playground,
> 

Re: [swift-evolution] URL Literals

2016-12-19 Thread David Sweeris via swift-evolution

> On Dec 19, 2016, at 1:26 AM, Xiaodi Wu  wrote:
> 
> URLs are unlikely to be something that can be validated by regex. See, for 
> instance, this discussion: 
>  >. The full spec is 
> here: >. If Swift 
> were to implement parsing of URLs at the level of the compiler or core 
> library, I'd expect it to be the full spec, as we do with Unicode.
> 
> 
> On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution 
> > wrote:
> Howdy,
>   Yes, I was also intrigued by the “Regex” validation mentioned in 
> another post.  It could offer a convenient way to get some literals support 
> in without the headaches associated with the constexpr C++ approach.
>   I’m curious, though, how many types can we image in can be validated by 
> this method?  If it really is just URL’s, then I’d actually lean towards 
> making this a compiler magic feature.
> 
>   Someone else mentioned fetching the URL’s for a preview.  Given that we 
> might be coding “deletes” in URL’s (yes, I recently met a backend developer 
> who coded a delete as a GET), I really highly suggest we not ping people’s 
> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO, 
> verifying that a service is active isn’t really the Swift compiler’s job.  It 
> might happen as part of coordinated run-time tests, which sometimes have to 
> be balanced to keep test data correct, something the IDE wouldn’t know how to 
> enforce correctly.
> -Ben
> 
>> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution 
>> > wrote:
>> 
>> 
>>> On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution 
>>> > wrote:
>>> 
>>> I'd love a fleshed out elegant example for URL that shows what a complete 
>>> implementation of that special init method would look like. 
>> 
>> Sorry this took so long… the weekend kinda got away from me.
>> 
>> Anyway, I was thinking something like this (which has been very simplified 
>> on account of my regexing being sub-sketchy, and me not knowing exactly 
>> what’s valid in an URL anyway):
>> #literalpatterns += (name: “URLLiteralType”, components: (name: url, type: 
>> StringLiteralType, pattern: 
>> “(http|https)://(www.)?[a-z|A-Z|0-9]+.(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
>>  protocol: ExpressibleByURLLiteral)
>> This would let the compiler know pretty much everything it needs to know… 
>> that the “new” type is called “URLLiteralType", that it starts out life as 
>> young StringLiteralType with a bright future in the computer industry, that 
>> in order to succeed it has to match a given pattern, and what protocol a 
>> type has to conform to in order to use an URLLiteral. In practice, the 
>> compiler would synthesize a struct containing the specified members and 
>> validate the literal with the specified pattern before making an “instance” 
>> of it (since we’re talking about literals and compile-time code here, I’m 
>> pretty sure that “instance" the wrong terminology… pardon my ignorance)
>> struct URLLiteralType: {
>> let url: StringLiteralType
>> }
>> A tuple would be better, IMHO, but according to the playground, 
>> single-element tuples can’t have element labels. As for the implementation 
>> of the init function:
>> init(urlLiteral value: URLLiteralType) {
>> let urlString = value.url
>> //Do whatever URL is doing now, except there’s no need to check for 
>> errors since the compiler pre-validated it for us
>> }
>> 
>> If it’d be more useful, the pattern could be split into multiple pieces:
>> #literalpatterns += (name: “URLLiteralType”,
>>  components: ((name: “`protocol`", type: 
>> StringLiteralType, pattern: “(http|https)”),
>>   (name: _,type: 
>> StringLiteralType, pattern: “://”),
>>   (name: “domain", type: 
>> StringLiteralType, pattern: “(www.)?[a-z|A-Z|0-9]+.(com|org|net)”),
>>   (name: “path”,   type: 
>> StringLiteralType, pattern: 
>> "(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”))
>>  protocol: ExpressibleByURLLiteral)
>> This would result in URLLiteralType looking like this:
>> struct URLLiteralType: {
>> let `protocol`: StringLiteralType
>> let domain: StringLiteralType
>> let path: StringLiteralType
>> }
>> And in the init would start out like this:
>> init(urlLiteral value: URLLiteralType) {
>> let protocolType = value.protocol
>> let domain = value.domain
>> let path = value.path
>> //Do whatever with the components
>> }
>> 
>> The “base” types of literals 

Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
On Mon, Dec 19, 2016 at 8:47 AM, Micah Hainline via swift-evolution <
swift-evolution@swift.org> wrote:

> Regarding validation of resources being reachable or existing, I think we
> should take that right off the table, for all types of URLs. Firstly,
> because it could be very error prone. Consider even the basic case of the
> deployment environment having access to the resource while the build
> environment does not. Consider the resource being available at run time but
> not compile time. That applies to file urls and every other kind.
>

File literals already do this, don't they?


> Secondly, it would be dangerous on many levels.
>
> On Mon, Dec 19, 2016 at 3:39 AM, Xiaodi Wu  wrote:
>
>> On Mon, Dec 19, 2016 at 1:55 AM, Benjamin Spratling 
>> wrote:
>>
>>> Howdy,
>>> I'm definitely on the "no force unwrapping bandwagon".  And I also
>>> see a huge difference in force-unwrapping a value derived from a literal,
>>> which can be unit tested, and force-unwrapping a value determined at run
>>> time, which might fail validation.  That's where I draw the line.
>>>
>>> I have seen some good developers "think" they "know" the value can't be
>>> nil, and they were just wrong.
>>>
>>
>> Well, sure, but the fault originated with the good developer being wrong,
>> not with `!`. All I'm saying is, there are legitimate use cases where one
>> intends to have this behavior:
>>
>> ```
>> guard let foo = bar else {
>>   fatalError() // Bye.
>> }
>> ```
>>
>> In those cases, it is perfectly legitimate to write:
>>
>> ```
>> let foo = bar!
>> ```
>>
>> But when we can specifically run a unit test with 0 inputs on the value,
>>> then falsification of nullability is easy.
>>>
>>> -Ben
>>>
>>> Sent from my iPhone.
>>>
>>> On Dec 16, 2016, at 7:30 PM, Xiaodi Wu via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> On Fri, Dec 16, 2016 at 7:01 PM, Micah Hainline <
>>> micah.hainl...@gmail.com> wrote:
>>>
 It's not super strong, but it's as strong as the URL type itself.

 Even if I do checking related to the resource being unavailable, I also
 have to do checking to account for the possibility of a nil URL. The two
 checks aren't closely related.

>>>
>>> When you use a URL, what would you do differently when a resource is
>>> unavailable versus when the URL is malformed, especially if you're
>>> hardcoding the URL?
>>>
>>> It does help to have one of them accounted for by the compiler if
 possible.

 I'm trying to teach some less experienced developers to think of
 force-unwrapping as a code smell,

>>>
>>> There have been a few people who have said a similar thing on the list,
>>> but I don't think this is the official line about force-unwrapping. Force
>>> unwrapping is an explicitly supported part of the language that has its
>>> uses. If you *know* at the time of writing that a failable initializer
>>> should never fail, then `!` is an expressive, clear, concise, entirely
>>> appropriate, and I would even say the *best* way of indicating that to your
>>> reader.
>>>
>>> It should be noted that `let url = URL(string: "http://example.com/;)!`
>>> is one example of this usage, but not at all the only one. I have
>>> previously written, for example, `"L".cString(using: .utf8)!`. This is also
>>> no code smell, as what I'm doing is stating my absolute confidence (and
>>> indicating that confidence to the reader) that the letter L can be encoded
>>> using UTF-8.
>>>
>>> but it's not the best to have to say "except for URLs". I realize the
 utility of the proposed change is reasonably small, but I also think it's
 purely additive and consistent with the rest of the language. 

 On Dec 16, 2016, at 6:45 PM, Xiaodi Wu  wrote:

 On Fri, Dec 16, 2016 at 5:54 PM, Micah Hainline via swift-evolution <
 swift-evolution@swift.org> wrote:

> True, but it's not at all about brevity, it's about type-safety and
> getting compile-time checking rather than runtime checking of the validity
> of the URL structure.
>

 While I understand that what you're after is compile-time checking of
 validity, I'm not convinced that it is materially useful. I also don't see
 how it's contributing to type safety. Perhaps you could illuminate what use
 case has persuaded you of these things? Here's my thinking:

 Nine times out of ten when I mistype a URL, or paste only a fragment of
 a URL, it's a mistake that results in a plausible but unintended URL and a
 compile-time check for validity will not help at all. To guard against such
 an error, I need to write tests anyway and could never depend on the
 compiler. In fact, I'd imagine that doing anything useful with a URL--even
 a hardcoded one--will require some thought as to how to deal with error
 handling at runtime. How is it helpful to have only the lowest bar (a
 technically 

Re: [swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Derrick Ho via swift-evolution
struct Person {
Var name: String = ""

func with(name n: String) -> Person {
var a = self
a.name = name
return a
}
}

let andy = Person().with(name: "Andy")
let brandon = andy.with(name: "Brandon")
On Mon, Dec 19, 2016 at 10:28 AM Andy Chou via swift-evolution <
swift-evolution@swift.org> wrote:

> I like that structs are value types in Swift, this encourages the use of
> immutable data. O'Caml has an operator "with" that allows for copying an
> existing struct with a change to one field. I looked at Lenses for this
> functionality and it seems like a lot to digest for something so simple. I
> also tried to implement this using a constructor, or a function, and it was
> not obvious how to do so without a lot of code duplication.
>
> What's I'm looking for is something like this (not necessarily with this
> syntax):
>
> struct Person {
> let name: String
> let address: String
> let phone: String
> }
>
> func f() {
> let andy = Person(name: "Andy", address: "1 Battery St., San
> Francisco, CA", phone: "1234567")
> let chris = andy.with(name: "Chris")
> let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
> }
>
> I tried to implement a "with" function like this but default arguments
> cannot reference properties of self. Same problem trying to do this in a
> constructor.
>
> Obviously it's possible to create an entirely new Person specifying the
> values from an existing Person, but this is very tedious with structures
> with many properties.
>
> Anyone taken a look at this before? Any suggestions?
>
> Andy
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] "with" operator a la O'Caml?

2016-12-19 Thread Andy Chou via swift-evolution
I like that structs are value types in Swift, this encourages the use of 
immutable data. O'Caml has an operator "with" that allows for copying an 
existing struct with a change to one field. I looked at Lenses for this 
functionality and it seems like a lot to digest for something so simple. I also 
tried to implement this using a constructor, or a function, and it was not 
obvious how to do so without a lot of code duplication.

What's I'm looking for is something like this (not necessarily with this 
syntax):

struct Person {
let name: String
let address: String
let phone: String
}

func f() {
let andy = Person(name: "Andy", address: "1 Battery St., San Francisco, 
CA", phone: "1234567")
let chris = andy.with(name: "Chris")
let dave = andy.with(address: "50 Townsend St., San Francisco, CA")
}

I tried to implement a "with" function like this but default arguments cannot 
reference properties of self. Same problem trying to do this in a constructor.

Obviously it's possible to create an entirely new Person specifying the values 
from an existing Person, but this is very tedious with structures with many 
properties.

Anyone taken a look at this before? Any suggestions?

Andy

___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Swift Closure still inconsistent -- tuple names need to be in curly brackets, single parameter needs to be in parentheses

2016-12-19 Thread Vip Malixi via swift-evolution
When using Closures in Swift, you declare the parameter names inside the curly 
brackets. How come for tuples you don't, but declare them outside? Also, why do 
single parameters not need parentheses? This makes Swift inconsistent, e.g.
var oneParameterAndMultipleReturn: ([Int]) -> (even:[Int], odd:[Int]) = { 
numbers -> ([Int], [Int]) in     var evenNumberArray = [Int]()    var 
oddNumberArray = [Int]()
    for number in numbers {        number % 2 == 0 ? 
evenNumberArray.append(number) : oddNumberArray.append(number)    }
    return (evenNumberArray, oddNumberArray)}
for consistency, I suggest tuple names should be in curly brackets where you 
also declare parameter names. Also, again for consistency and clarity, 
parameters in Closures should always be surrounded by parentheses, even single 
parameters:
var oneParameterAndMultipleReturn: ([Int]) -> ([Int], [Int]) = { (numbers) -> 
(even:[Int], odd:[Int]) in     var evenNumberArray = [Int]()    var 
oddNumberArray = [Int]()
    for number in numbers {        number % 2 == 0 ? 
evenNumberArray.append(number) : oddNumberArray.append(number)    }
    return (evenNumberArray, oddNumberArray)}___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] URL Literals

2016-12-19 Thread Micah Hainline via swift-evolution
I would like to be able to create a URL literal that is compile-time
checked for correct format. This would help avoid code like this:

let url = URL(string: "https://example.com;)!

The cleanest way I can think of doing that would be to introduce a new
macro structure similar to #selector, though I'm open to other ideas.
I would think it should take a quoted literal string to avoid
problems. That would look like this:

let url = #url("https://example.com;)

What does everyone think of that idea?

Micah Hainline
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] URL Literals

2016-12-19 Thread Micah Hainline via swift-evolution
Regarding validation of resources being reachable or existing, I think we
should take that right off the table, for all types of URLs. Firstly,
because it could be very error prone. Consider even the basic case of the
deployment environment having access to the resource while the build
environment does not. Consider the resource being available at run time but
not compile time. That applies to file urls and every other kind.

Secondly, it would be dangerous on many levels.

On Mon, Dec 19, 2016 at 3:39 AM, Xiaodi Wu  wrote:

> On Mon, Dec 19, 2016 at 1:55 AM, Benjamin Spratling 
> wrote:
>
>> Howdy,
>> I'm definitely on the "no force unwrapping bandwagon".  And I also
>> see a huge difference in force-unwrapping a value derived from a literal,
>> which can be unit tested, and force-unwrapping a value determined at run
>> time, which might fail validation.  That's where I draw the line.
>>
>> I have seen some good developers "think" they "know" the value can't be
>> nil, and they were just wrong.
>>
>
> Well, sure, but the fault originated with the good developer being wrong,
> not with `!`. All I'm saying is, there are legitimate use cases where one
> intends to have this behavior:
>
> ```
> guard let foo = bar else {
>   fatalError() // Bye.
> }
> ```
>
> In those cases, it is perfectly legitimate to write:
>
> ```
> let foo = bar!
> ```
>
> But when we can specifically run a unit test with 0 inputs on the value,
>> then falsification of nullability is easy.
>>
>> -Ben
>>
>> Sent from my iPhone.
>>
>> On Dec 16, 2016, at 7:30 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> On Fri, Dec 16, 2016 at 7:01 PM, Micah Hainline > > wrote:
>>
>>> It's not super strong, but it's as strong as the URL type itself.
>>>
>>> Even if I do checking related to the resource being unavailable, I also
>>> have to do checking to account for the possibility of a nil URL. The two
>>> checks aren't closely related.
>>>
>>
>> When you use a URL, what would you do differently when a resource is
>> unavailable versus when the URL is malformed, especially if you're
>> hardcoding the URL?
>>
>> It does help to have one of them accounted for by the compiler if
>>> possible.
>>>
>>> I'm trying to teach some less experienced developers to think of
>>> force-unwrapping as a code smell,
>>>
>>
>> There have been a few people who have said a similar thing on the list,
>> but I don't think this is the official line about force-unwrapping. Force
>> unwrapping is an explicitly supported part of the language that has its
>> uses. If you *know* at the time of writing that a failable initializer
>> should never fail, then `!` is an expressive, clear, concise, entirely
>> appropriate, and I would even say the *best* way of indicating that to your
>> reader.
>>
>> It should be noted that `let url = URL(string: "http://example.com/;)!`
>> is one example of this usage, but not at all the only one. I have
>> previously written, for example, `"L".cString(using: .utf8)!`. This is also
>> no code smell, as what I'm doing is stating my absolute confidence (and
>> indicating that confidence to the reader) that the letter L can be encoded
>> using UTF-8.
>>
>> but it's not the best to have to say "except for URLs". I realize the
>>> utility of the proposed change is reasonably small, but I also think it's
>>> purely additive and consistent with the rest of the language. 
>>>
>>> On Dec 16, 2016, at 6:45 PM, Xiaodi Wu  wrote:
>>>
>>> On Fri, Dec 16, 2016 at 5:54 PM, Micah Hainline via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
 True, but it's not at all about brevity, it's about type-safety and
 getting compile-time checking rather than runtime checking of the validity
 of the URL structure.

>>>
>>> While I understand that what you're after is compile-time checking of
>>> validity, I'm not convinced that it is materially useful. I also don't see
>>> how it's contributing to type safety. Perhaps you could illuminate what use
>>> case has persuaded you of these things? Here's my thinking:
>>>
>>> Nine times out of ten when I mistype a URL, or paste only a fragment of
>>> a URL, it's a mistake that results in a plausible but unintended URL and a
>>> compile-time check for validity will not help at all. To guard against such
>>> an error, I need to write tests anyway and could never depend on the
>>> compiler. In fact, I'd imagine that doing anything useful with a URL--even
>>> a hardcoded one--will require some thought as to how to deal with error
>>> handling at runtime. How is it helpful to have only the lowest bar (a
>>> technically valid URL format) ensured at compile time instead of runtime?
>>> By contrast, Swift selectors help to guarantee that any particular function
>>> I'm referring to actually exists; when that is ensured at compile time, I
>>> know it will be the case at runtime. There's no 

Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
On Mon, Dec 19, 2016 at 1:55 AM, Benjamin Spratling 
wrote:

> Howdy,
> I'm definitely on the "no force unwrapping bandwagon".  And I also see
> a huge difference in force-unwrapping a value derived from a literal, which
> can be unit tested, and force-unwrapping a value determined at run time,
> which might fail validation.  That's where I draw the line.
>
> I have seen some good developers "think" they "know" the value can't be
> nil, and they were just wrong.
>

Well, sure, but the fault originated with the good developer being wrong,
not with `!`. All I'm saying is, there are legitimate use cases where one
intends to have this behavior:

```
guard let foo = bar else {
  fatalError() // Bye.
}
```

In those cases, it is perfectly legitimate to write:

```
let foo = bar!
```

But when we can specifically run a unit test with 0 inputs on the value,
> then falsification of nullability is easy.
>
> -Ben
>
> Sent from my iPhone.
>
> On Dec 16, 2016, at 7:30 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> On Fri, Dec 16, 2016 at 7:01 PM, Micah Hainline 
> wrote:
>
>> It's not super strong, but it's as strong as the URL type itself.
>>
>> Even if I do checking related to the resource being unavailable, I also
>> have to do checking to account for the possibility of a nil URL. The two
>> checks aren't closely related.
>>
>
> When you use a URL, what would you do differently when a resource is
> unavailable versus when the URL is malformed, especially if you're
> hardcoding the URL?
>
> It does help to have one of them accounted for by the compiler if possible.
>>
>> I'm trying to teach some less experienced developers to think of
>> force-unwrapping as a code smell,
>>
>
> There have been a few people who have said a similar thing on the list,
> but I don't think this is the official line about force-unwrapping. Force
> unwrapping is an explicitly supported part of the language that has its
> uses. If you *know* at the time of writing that a failable initializer
> should never fail, then `!` is an expressive, clear, concise, entirely
> appropriate, and I would even say the *best* way of indicating that to your
> reader.
>
> It should be noted that `let url = URL(string: "http://example.com/;)!`
> is one example of this usage, but not at all the only one. I have
> previously written, for example, `"L".cString(using: .utf8)!`. This is also
> no code smell, as what I'm doing is stating my absolute confidence (and
> indicating that confidence to the reader) that the letter L can be encoded
> using UTF-8.
>
> but it's not the best to have to say "except for URLs". I realize the
>> utility of the proposed change is reasonably small, but I also think it's
>> purely additive and consistent with the rest of the language. 
>>
>> On Dec 16, 2016, at 6:45 PM, Xiaodi Wu  wrote:
>>
>> On Fri, Dec 16, 2016 at 5:54 PM, Micah Hainline via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> True, but it's not at all about brevity, it's about type-safety and
>>> getting compile-time checking rather than runtime checking of the validity
>>> of the URL structure.
>>>
>>
>> While I understand that what you're after is compile-time checking of
>> validity, I'm not convinced that it is materially useful. I also don't see
>> how it's contributing to type safety. Perhaps you could illuminate what use
>> case has persuaded you of these things? Here's my thinking:
>>
>> Nine times out of ten when I mistype a URL, or paste only a fragment of a
>> URL, it's a mistake that results in a plausible but unintended URL and a
>> compile-time check for validity will not help at all. To guard against such
>> an error, I need to write tests anyway and could never depend on the
>> compiler. In fact, I'd imagine that doing anything useful with a URL--even
>> a hardcoded one--will require some thought as to how to deal with error
>> handling at runtime. How is it helpful to have only the lowest bar (a
>> technically valid URL format) ensured at compile time instead of runtime?
>> By contrast, Swift selectors help to guarantee that any particular function
>> I'm referring to actually exists; when that is ensured at compile time, I
>> know it will be the case at runtime. There's no corresponding guarantee by
>> having a compile-time check for URL validity that the resource pointed to
>> will actually exist. That the nonexistent resource was denoted by a string
>> that had the correct format of a URL is cold comfort, no?
>>
>>
>> On Dec 16, 2016, at 5:50 PM, Derrick Ho  wrote:
>>>
>>> let url = URL(string: "https://example.com;)!
>>>
>>> let url = #url("https://example.com;)
>>>
>>> Are not that different in length. It really isn't saving you much.
>>>
>>> I suppose you can try overloading an operator to get something to the
>>> effect you want.
>>> On Fri, Dec 16, 2016 at 6:19 PM Micah Hainline via swift-evolution <
>>> 

Re: [swift-evolution] URL Literals

2016-12-19 Thread Xiaodi Wu via swift-evolution
URLs are unlikely to be something that can be validated by regex. See, for
instance, this discussion: <
https://webkit.org/blog/7086/url-parsing-in-webkit/>. The full spec is
here: . If Swift were to implement parsing of
URLs at the level of the compiler or core library, I'd expect it to be the
full spec, as we do with Unicode.


On Mon, Dec 19, 2016 at 2:26 AM, Benjamin Spratling via swift-evolution <
swift-evolution@swift.org> wrote:

> Howdy,
> Yes, I was also intrigued by the “Regex” validation mentioned in another
> post.  It could offer a convenient way to get some literals support in
> without the headaches associated with the constexpr C++ approach.
> I’m curious, though, how many types can we image in can be validated by
> this method?  If it really is just URL’s, then I’d actually lean towards
> making this a compiler magic feature.
>
> Someone else mentioned fetching the URL’s for a preview.  Given that we
> might be coding “deletes” in URL’s (yes, I recently met a backend developer
> who coded a delete as a GET), I really highly suggest we not ping people’s
> API’s artificially.  At least we shouldn’t for non-file-scheme URLs.  IMHO,
> verifying that a service is active isn’t really the Swift compiler’s job.
> It might happen as part of coordinated run-time tests, which sometimes have
> to be balanced to keep test data correct, something the IDE wouldn’t know
> how to enforce correctly.
> -Ben
>
> On Dec 19, 2016, at 1:41 AM, David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I'd love a fleshed out elegant example for URL that shows what a complete
> implementation of that special init method would look like.
>
>
> Sorry this took so long… the weekend kinda got away from me.
>
> Anyway, I was thinking something like this (which has been very simplified
> on account of my regexing being sub-sketchy, and me not knowing exactly
> what’s valid in an URL anyway):
>
> #literalpatterns += (name: “URLLiteralType”, components: (name: url,
> type: StringLiteralType, pattern: “(http|https)://(www.)?[a-z|A-Z|0-9]+
> .(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
> protocol: ExpressibleByURLLiteral)
>
> This would let the compiler know pretty much everything it needs to know…
> that the “new” type is called “URLLiteralType", that it starts out life as
> young StringLiteralType with a bright future in the computer industry, that
> in order to succeed it has to match a given pattern, and what protocol a
> type has to conform to in order to use an URLLiteral. In practice, the
> compiler would synthesize a struct containing the specified members and
> validate the literal with the specified pattern before making an “instance”
> of it (since we’re talking about literals and compile-time code here, I’m
> pretty sure that “instance" the wrong terminology… pardon my ignorance)
>
> struct URLLiteralType: {
> let url: StringLiteralType
> }
>
> A tuple would be better, IMHO, but according to the playground,
> single-element tuples can’t have element labels. As for the
> implementation of the init function:
>
> init(urlLiteral value: URLLiteralType) {
> let urlString = value.url
> //Do whatever URL is doing now, except there’s no need to check for
> errors since the compiler pre-validated it for us
> }
>
>
> If it’d be more useful, the pattern could be split into multiple pieces:
>
> #literalpatterns += (name: “URLLiteralType”,
>  components: ((name: “`protocol`", type:
> StringLiteralType, pattern: “(http|https)”),
>   (name: _,type:
> StringLiteralType, pattern: “://”),
>   (name: “domain", type:
> StringLiteralType, pattern: “(www.)?[a-z|A-Z|0-9]+.(com|org|net)”),
>   (name: “path”,   type:
> StringLiteralType, pattern: "(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.
> [a-z|A-Z|0-9]+)?”))
>  protocol: ExpressibleByURLLiteral)
>
> This would result in URLLiteralType looking like this:
>
> struct URLLiteralType: {
> let `protocol`: StringLiteralType
> let domain: StringLiteralType
> let path: StringLiteralType
> }
>
> And in the init would start out like this:
>
> init(urlLiteral value: URLLiteralType) {
> let protocolType = value.protocol
> let domain = value.domain
> let path = value.path
> //Do whatever with the components
> }
>
>
> The “base” types of literals like Int or String that don’t refine
> pre-existing literal types would still need a bit of compiler magic (or at
> least a different mechanism for becoming actual types), but as long as a
> type doesn’t take advantage of reference semantics in its stored properties
> or something, I *think* pretty much any data type could become
> “literalizeable” with something like this. Oh, and there’s 

Re: [swift-evolution] URL Literals

2016-12-19 Thread Rien via swift-evolution
I like where this is going!
+1

Regards,
Rien

Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Swiftrien
Project: http://swiftfire.nl




> On 19 Dec 2016, at 08:41, David Sweeris via swift-evolution 
>  wrote:
> 
> 
>> On Dec 17, 2016, at 1:12 PM, Micah Hainline via swift-evolution 
>>  wrote:
>> 
>> I'd love a fleshed out elegant example for URL that shows what a complete 
>> implementation of that special init method would look like. 
> 
> Sorry this took so long… the weekend kinda got away from me.
> 
> Anyway, I was thinking something like this (which has been very simplified on 
> account of my regexing being sub-sketchy, and me not knowing exactly what’s 
> valid in an URL anyway):
> #literalpatterns += (name: “URLLiteralType”, components: (name: url, type: 
> StringLiteralType, pattern: 
> “(http|https)://(www.)?[a-z|A-Z|0-9]+.(com|org|net)(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”),
>  protocol: ExpressibleByURLLiteral)
> This would let the compiler know pretty much everything it needs to know… 
> that the “new” type is called “URLLiteralType", that it starts out life as 
> young StringLiteralType with a bright future in the computer industry, that 
> in order to succeed it has to match a given pattern, and what protocol a type 
> has to conform to in order to use an URLLiteral. In practice, the compiler 
> would synthesize a struct containing the specified members and validate the 
> literal with the specified pattern before making an “instance” of it (since 
> we’re talking about literals and compile-time code here, I’m pretty sure that 
> “instance" the wrong terminology… pardon my ignorance)
> struct URLLiteralType: {
> let url: StringLiteralType
> }
> A tuple would be better, IMHO, but according to the playground, 
> single-element tuples can’t have element labels. As for the implementation of 
> the init function:
> init(urlLiteral value: URLLiteralType) {
> let urlString = value.url
> //Do whatever URL is doing now, except there’s no need to check for 
> errors since the compiler pre-validated it for us
> }
> 
> If it’d be more useful, the pattern could be split into multiple pieces:
> #literalpatterns += (name: “URLLiteralType”,
>  components: ((name: “`protocol`", type: 
> StringLiteralType, pattern: “(http|https)”),
>   (name: _,type: 
> StringLiteralType, pattern: “://”),
>   (name: “domain", type: 
> StringLiteralType, pattern: “(www.)?[a-z|A-Z|0-9]+.(com|org|net)”),
>   (name: “path”,   type: 
> StringLiteralType, pattern: 
> "(/[a-z|A-Z|0-9]+)*(/[a-z|A-Z|0-9]+.[a-z|A-Z|0-9]+)?”))
>  protocol: ExpressibleByURLLiteral)
> This would result in URLLiteralType looking like this:
> struct URLLiteralType: {
> let `protocol`: StringLiteralType
> let domain: StringLiteralType
> let path: StringLiteralType
> }
> And in the init would start out like this:
> init(urlLiteral value: URLLiteralType) {
> let protocolType = value.protocol
> let domain = value.domain
> let path = value.path
> //Do whatever with the components
> }
> 
> The “base” types of literals like Int or String that don’t refine 
> pre-existing literal types would still need a bit of compiler magic (or at 
> least a different mechanism for becoming actual types), but as long as a type 
> doesn’t take advantage of reference semantics in its stored properties or 
> something, I *think* pretty much any data type could become “literalizeable” 
> with something like this. Oh, and there’s nothing particularly magical about 
> regular expressions as far as this idea is concerned; they’re just usually 
> the first thing that comes to mind when I think of pattern matching in a 
> string. 
> 
> I know this looks like a lot of code, but the scary-looking parts with the 
> regex stuff only has to be written once for each “type” of literal… types 
> that want to be expressible by such a literal just have to write an init 
> function.
> 
> 
> 
> 
> 
> While I was writing this up, it occurred to me that another solution would be 
> to have a set of "ExpressibleByValidated*Literal” protocols, where the init 
> is failable and has to be 
> @pure/@constexpr/@whateverthecompilerneedstorunitatcompiletime. That way the 
> literal can be validated simply by calling the init and checking if it 
> returns nil. Make `URL` conform to `ExpressibleByValidatedStringLiteral`, and 
> you'll get the complie-time validation functionality just by copying 
> whatever’s in the current `URL.init?(string: String)` function.
> 
> - Dave Sweeris
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___