Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Douglas Gregor via swift-evolution

> On Apr 13, 2017, at 2:42 PM, David Hart via swift-evolution 
>  wrote:
> 
> Looking good. A few comments inline:
> 
>> On 13 Apr 2017, at 22:17, Ben Cohen via swift-evolution 
>> > wrote:
>> Comparable
>> 
>> Comparable will be changed to have a new ternary comparison method: 
>> compare(_ other: Self) -> ComparisonResult. x.compare(y) specifies where to 
>> place x relative to y. So if it yields .orderedAscending, then x comes 
>> before y. This will be considered the new “main” dispatch point of 
>> Comparable that implementors should provide.
>> 
>> Most code will continue to use < or ==, as it will be optimal for their 
>> purposes. However code that needs to make a three-way branch on comparison 
>> can use the potentially more efficient compare. Note that compare is only 
>> expected to be more efficient in this specific case. If a two-way branch is 
>> all that’s being done, < will be more efficient in many cases (if only 
>> because it’s easier for the optimizer).
>> 
>> For backwards compatibility reasons, compare will have a default 
>> implementation defined in terms of <, but to enable only using compare, < 
>> and == will also have default implementations in terms of compare.
>> 
>> The compiler will verify that either compare, or < and ==, are provided by 
>> every type that claims to conform to Comparable. This will be done in some 
>> unspecified way unavailable outside the standard library (it can be made 
>> available to in the future, but that’s an unnecessary distraction for this 
>> proposal).
>> 
> It feels weird to me to jump through all these hoops just for backwards 
> compatibility. Seeing how even big projects might only have several 
> Comparable conformances, wouldn’t it be worth removing the default 
> implementation of compare and removing < from Comparable?

The core team cares a *lot* about backwards compatibility. The engineering 
effort involved in implementing this mutually-exclusive check is very small 
compared with the benefits of maintaining compatibility.

- Doug


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


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
On Thu, Apr 13, 2017 at 11:00 PM, Jonathan Hull  wrote:

> Oh come on.  You are exaggerating the issue here.  As I said, there isn’t
> really any extra maintenance needed and people are already familiar with
> their meaning.  It isn’t like they have to learn new archaic symbols. Even
> HTML defines a special code for them because their use is common.  There is
> only one reasonable implementation, and they can’t have another meaning
> without causing confusion.  They are pretty easy to type on most keyboards.
>
> I view the gain in clarity/readability as functionality.
>

It is not a gain but a loss in clarity, because it introduces two spellings
for the same thing where now there is one.

Using ‘+’ instead of ‘adding(to:)’ may not have extra functionality by your
> definition, but it sure makes long equations easier for me to parse.
>

Again, _instead of_ is not the problem, but _in addition to_ is. We have
one way to spell less-than-or-equal-to in the standard library, and it is
`<=`. That goes again to the "opinionated" part of Swift language design.

The trampolining design that was required for `FloatingPoint` (with methods
like `dividing(by:)`, etc.) was an unfortunate artifact of that protocol
being approved before static operators; those methods were once necessary
for functionality and today are a wart that should not be emulated.

This is something that should have been there since the beginning.  I know
> it isn’t a high priority, but since we are re-writing the protocol anyway,
> we should take the 3 seconds it takes to add them and do it.  I am happy to
> provide the implementations if needed.
>
> Thanks,
> Jon
>
>
> On Apr 13, 2017, at 8:09 PM, Xiaodi Wu  wrote:
>
> On Thu, Apr 13, 2017 at 7:51 PM, Jonathan Hull  wrote:
>
>> I think “vastly” is vastly overstating it, especially since they are not
>> customization points… merely aliases.
>>
>
> It increases the number of methods on Comparable from 5 to 8, and it
> increases the number of standard operators (which will already expand if
> one-sided ranges are approved), with no functionality gain whatsoever. It
> doubles the number of ways to write three operators. And it expands the
> standard operators past the ASCII range, which was a choice deliberately
> not taken during the debate about how to name SetAlgebra members. If this
> is not a vast expansion, I do not know what is.
>
> There is nothing else those operators could do without causing confusion.
>> Swift favors clarity, and these operators are much more clear (which I
>> count as a benefit).  Also ‘<=‘ looks like an arrow, which I find very
>> distracting in code, as my eye wants to follow it.
>>
>> I do use this myself in application code, but I can’t add it to my
>> framework code without potentially clashing with others (or myself) who
>> have added the same behavior for themselves.  Even though the
>> implementations are exactly the same, it becomes ambiguous which of the
>> (identical) definitions should be used.  Having it in the library would
>> mean that everyone would just use that version (and there is only one
>> reasonable implementation, so it wont limit anyone).
>>
>
> If it were in high demand, a de-facto standard would have arisen by now
> vending these symbols as a standalone library. For now, nothing stops you
> from defining them for internal use in your library.
>
> I really don’t think there is danger of harm here as you seem to be
>> implying. Anyone who sees ‘≤’ will know what it means, even if they aren’t
>> familiar with Swift.  If the implementations point to ‘<=‘, etc… then
>> nothing will get out of sync.  There really isn’t any extra maintenance
>> needed.
>>
>> Thanks,
>> Jon
>>
>>
>> On Apr 13, 2017, at 5:03 PM, Xiaodi Wu  wrote:
>>
>> On Thu, Apr 13, 2017 at 7:02 PM, Jonathan Hull via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> This is a sugar request, but if we are rearranging these things anyway,
>>> can we *please* add the ‘≤’, ‘≥’, and ‘≠’ operators to comparable.  I know
>>> they would do the same thing as ‘<=‘, ‘>=‘, and ‘!=‘, but they can’t really
>>> be used for anything else without being confusing (because they literally
>>> have that meaning in mathematics), and they make my code so much more
>>> readable.
>>>
>>
>> This is vastly increasing API surface area for every user of Swift for
>> literally no functionality. Why isn't it sufficient that Swift allows you
>> to do this for yourself without restriction?
>>
>>
>>>
>>> Thanks,
>>> Jon
>>>
>>>
>>>
>>> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> Online copy here:
>>>
>>> https://github.com/airspeedswift/swift-evolution/blob/fa0071
>>> 38a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md
>>>
>>>
>>>
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org
>>> 

Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jonathan Hull via swift-evolution
Oh come on.  You are exaggerating the issue here.  As I said, there isn’t 
really any extra maintenance needed and people are already familiar with their 
meaning.  It isn’t like they have to learn new archaic symbols. Even HTML 
defines a special code for them because their use is common.  There is only one 
reasonable implementation, and they can’t have another meaning without causing 
confusion.  They are pretty easy to type on most keyboards.

I view the gain in clarity/readability as functionality.  Using ‘+’ instead of 
‘adding(to:)’ may not have extra functionality by your definition, but it sure 
makes long equations easier for me to parse.  This is something that should 
have been there since the beginning.  I know it isn’t a high priority, but 
since we are re-writing the protocol anyway, we should take the 3 seconds it 
takes to add them and do it.  I am happy to provide the implementations if 
needed.

Thanks,
Jon


> On Apr 13, 2017, at 8:09 PM, Xiaodi Wu  wrote:
> 
> On Thu, Apr 13, 2017 at 7:51 PM, Jonathan Hull  > wrote:
> I think “vastly” is vastly overstating it, especially since they are not 
> customization points… merely aliases.
> 
> It increases the number of methods on Comparable from 5 to 8, and it 
> increases the number of standard operators (which will already expand if 
> one-sided ranges are approved), with no functionality gain whatsoever. It 
> doubles the number of ways to write three operators. And it expands the 
> standard operators past the ASCII range, which was a choice deliberately not 
> taken during the debate about how to name SetAlgebra members. If this is not 
> a vast expansion, I do not know what is.
> 
> There is nothing else those operators could do without causing confusion.  
> Swift favors clarity, and these operators are much more clear (which I count 
> as a benefit).  Also ‘<=‘ looks like an arrow, which I find very distracting 
> in code, as my eye wants to follow it.
> 
> I do use this myself in application code, but I can’t add it to my framework 
> code without potentially clashing with others (or myself) who have added the 
> same behavior for themselves.  Even though the implementations are exactly 
> the same, it becomes ambiguous which of the (identical) definitions should be 
> used.  Having it in the library would mean that everyone would just use that 
> version (and there is only one reasonable implementation, so it wont limit 
> anyone).
> 
> If it were in high demand, a de-facto standard would have arisen by now 
> vending these symbols as a standalone library. For now, nothing stops you 
> from defining them for internal use in your library.
> 
> I really don’t think there is danger of harm here as you seem to be implying. 
> Anyone who sees ‘≤’ will know what it means, even if they aren’t familiar 
> with Swift.  If the implementations point to ‘<=‘, etc… then nothing will get 
> out of sync.  There really isn’t any extra maintenance needed.
> 
> Thanks,
> Jon
> 
> 
>> On Apr 13, 2017, at 5:03 PM, Xiaodi Wu > > wrote:
>> 
>> On Thu, Apr 13, 2017 at 7:02 PM, Jonathan Hull via swift-evolution 
>> > wrote:
>> This is a sugar request, but if we are rearranging these things anyway, can 
>> we *please* add the ‘≤’, ‘≥’, and ‘≠’ operators to comparable.  I know they 
>> would do the same thing as ‘<=‘, ‘>=‘, and ‘!=‘, but they can’t really be 
>> used for anything else without being confusing (because they literally have 
>> that meaning in mathematics), and they make my code so much more readable.
>> 
>> This is vastly increasing API surface area for every user of Swift for 
>> literally no functionality. Why isn't it sufficient that Swift allows you to 
>> do this for yourself without restriction?
>>  
>> 
>> Thanks,
>> Jon
>> 
>>  
>>> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution 
>>> > wrote:
>>> 
>>> Online copy here:
>>> 
>>> https://github.com/airspeedswift/swift-evolution/blob/fa007138a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md
>>>  
>>> 
>> 
>> ___
>> 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] [pitch] Comparison Reform

2017-04-13 Thread Jonathan Hull via swift-evolution
One more thought.  I am generally in favor of this proposal, but since it is in 
the pitch stage, I wanted to offer an alternative approach that I didn’t see 
mentioned.  Food for thought/discussion.

What if, instead of repurposing comparable (and adding new functions for 
options like case insensitive compare), we define a comparison metric (with all 
of the options built in) and then use that to get our comparison result.  
Comparable things would have a default metric that uses ‘<‘ and ‘==‘ to provide 
a comparison result.

The metric would have a method which takes two things and returns a 
ComparisonResult. The two things would usually be the same type, but wouldn’t 
necessarily have to be.

As a convenience, any type could have a compared(to:, using:) method where you 
pass a comparison metric to the using parameter and receive a ComparisonResult. 
 Comparable things could add a compared(with:) method and the spaceship 
operator <=>, which both use the default metric.

Pros:
• Would work without compiler alterations
• You can create metrics that compare items of different types
• Can setup the metric once for algorithms/comparisons with high setup cost
• Things like 'compare(to: other, using: .caseInsensitiveComparison)' fall out 
of the design without having to create/learn various different versions of 
compare on different types.
• Spaceship operator <=> for those who want it
• In some cases, it can provide a much more efficient implementation based on 
underlying structure. For example, you can get a metric from String/Unicode 
which is optimized for a particular view of that string (say ASCII).  Depending 
on the case, when one of the objects doesn’t match the optimized type, it can 
either convert or fallback to a more general algorithm… but it should provide a 
pretty big win when most of the objects have a known structure.

Cons:
• More protocols defined by the design
• Requires an extra struct/class to implement in non-standard cases (e.g. case 
insensitive compare)
• Probably something else I am missing

Thanks,
Jon



> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution 
>  wrote:
> 
> Online copy here:
> 
> https://github.com/airspeedswift/swift-evolution/blob/fa007138a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md
>  
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
On Thu, Apr 13, 2017 at 7:46 PM, Guillaume Lessard <
gless...@tffenterprises.com> wrote:

>
> > On Apr 13, 2017, at 18:18, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > `compare(_:)` does not merit a term-of-art exception when the Swift name
> is clearly `compared(to:)`.
>
> No; in full grammatical pedanticity it should be compared(with:).
> “compare to” is for dissimilar things.
> “compare with” is for similar things.
> (I’m not claiming that anyone cares, and I may have a traditional
> interpretation.)
>

I have read the entirety of the OED entry on "compare," and I have found no
evidence to support that. There are some usages that prefer "to" over
"with," and some vice versa, but it is not by degree of similarity.


> If the whole thing remains couched in terms of comparison, I prefer the
> function to be named compare(_:), because it’s such an everyday term. No
> one expects this action to possibly have a side effect.
>
> Cheers,
> Guillaume Lessard
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
On Thu, Apr 13, 2017 at 7:51 PM, Jonathan Hull  wrote:

> I think “vastly” is vastly overstating it, especially since they are not
> customization points… merely aliases.
>

It increases the number of methods on Comparable from 5 to 8, and it
increases the number of standard operators (which will already expand if
one-sided ranges are approved), with no functionality gain whatsoever. It
doubles the number of ways to write three operators. And it expands the
standard operators past the ASCII range, which was a choice deliberately
not taken during the debate about how to name SetAlgebra members. If this
is not a vast expansion, I do not know what is.

There is nothing else those operators could do without causing confusion.
> Swift favors clarity, and these operators are much more clear (which I
> count as a benefit).  Also ‘<=‘ looks like an arrow, which I find very
> distracting in code, as my eye wants to follow it.
>
> I do use this myself in application code, but I can’t add it to my
> framework code without potentially clashing with others (or myself) who
> have added the same behavior for themselves.  Even though the
> implementations are exactly the same, it becomes ambiguous which of the
> (identical) definitions should be used.  Having it in the library would
> mean that everyone would just use that version (and there is only one
> reasonable implementation, so it wont limit anyone).
>

If it were in high demand, a de-facto standard would have arisen by now
vending these symbols as a standalone library. For now, nothing stops you
from defining them for internal use in your library.

I really don’t think there is danger of harm here as you seem to be
> implying. Anyone who sees ‘≤’ will know what it means, even if they aren’t
> familiar with Swift.  If the implementations point to ‘<=‘, etc… then
> nothing will get out of sync.  There really isn’t any extra maintenance
> needed.
>
> Thanks,
> Jon
>
>
> On Apr 13, 2017, at 5:03 PM, Xiaodi Wu  wrote:
>
> On Thu, Apr 13, 2017 at 7:02 PM, Jonathan Hull via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> This is a sugar request, but if we are rearranging these things anyway,
>> can we *please* add the ‘≤’, ‘≥’, and ‘≠’ operators to comparable.  I know
>> they would do the same thing as ‘<=‘, ‘>=‘, and ‘!=‘, but they can’t really
>> be used for anything else without being confusing (because they literally
>> have that meaning in mathematics), and they make my code so much more
>> readable.
>>
>
> This is vastly increasing API surface area for every user of Swift for
> literally no functionality. Why isn't it sufficient that Swift allows you
> to do this for yourself without restriction?
>
>
>>
>> Thanks,
>> Jon
>>
>>
>>
>> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Online copy here:
>>
>> https://github.com/airspeedswift/swift-evolution/blob/fa0071
>> 38a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md
>>
>>
>>
>> ___
>> 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] [pitch] One-sided Ranges

2017-04-13 Thread Brent Royal-Gordon via swift-evolution
> On Apr 13, 2017, at 7:29 PM, Félix Cloutier via swift-evolution 
>  wrote:
> 
> template
> void foo(T... args)
> {
>   return bar(args...);
> }
> 
> In this bad but simple example, bar is called with the same* parameters as 
> foo. Parameter unpacking uses the postfix … operator.
> 
> * To some extent. Doing the right thing adds a lot of noise.


I want to see tuple splat and variadic generics one day, but I think partial 
ranges will be used more often. We can give parameter unpacking a heavier 
syntax.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [pitch] One-sided Ranges

2017-04-13 Thread Félix Cloutier via swift-evolution
template
void foo(T... args)
{
return bar(args...);
}

In this bad but simple example, bar is called with the same* parameters as foo. 
Parameter unpacking uses the postfix … operator.

* To some extent. Doing the right thing adds a lot of noise.

> Le 13 avr. 2017 à 11:18, David Sweeris  a écrit :
> 
> 
>> On Apr 12, 2017, at 20:31, Félix Cloutier via swift-evolution 
>>  wrote:
>> 
>> I don't have a strong opinion; are we sure enough that this is what we want 
>> the postfix operator … to be for? For instance, C++ uses it a lot with 
>> variadic templates.
> 
> I don't think the two usages conflict... maybe later if "literal values as 
> generic parameters" and "variadic generic parameters" get added, there might 
> be a problem involving variadic literal one-sided ranges, but otherwise we 
> should be good on that front... I think...
> 
> I should probably learn more about how C++ templates have changed since they 
> were first introduced.
> 
> - Dave Sweeris

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


[swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Robert Bennett via swift-evolution
We definitely should not alter the default subscript behavior of Array. 
Perhaps, it might be worthwhile to add a method `element(atIndex: Index) -> 
Element?` or some such method.

It's hard to say whether it would be worth it; the desired behavior can be 
achieved with `0..https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
Right; clearly, the difference between the proposed @_implements design and
yours will be subtle (but, when it strikes, a totally different function is
invoked) and it will be difficult for even advanced Swift users to
understand.
On Thu, Apr 13, 2017 at 20:29 Jaden Geller  wrote:

> Oh, I definitely overlooked that part. Thanks for that clarification! I
> had assumed the compiler changes were only necessary for allowing circular
> default implementations while still requiring at least one requirement be
> implemented.
>
> That said, it’s possible to implement something very, very similar without
> compiler changes:
>
> https://gist.github.com/JadenGeller/7566b3b64b5597ee57e8a509f6fc4bb3#file-context-swift-L43
>
> Cheers,
> Jaden Geller
>
> On Apr 13, 2017, at 5:58 PM, Xiaodi Wu  wrote:
>
> Jaden, the proposal literally says that a compiler feature named
> "@_implements" is necessary for the proposed design to work. You can see
> WIP for that feature in the apple/swift repo.
>
>
> On Thu, Apr 13, 2017 at 19:55 Jaden Geller  wrote:
>
>>
>> On Apr 13, 2017, at 5:18 PM, Xiaodi Wu via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Actually, the fact that this behavior cannot even be achieved without
>> currently non-existent compiler features means that it is not possible to
>> understand what's truly going on without reading *this document*, after
>> mastering *both* IEEE floating point *and* Swift
>> generics/protocols/extensions/static vs. dynamic dispatch. All to use `==`
>> correctly. Which is to say, most people will simply not even know if they
>> happen to be using the `==` they did not intend to use.
>>
>>
>> If I understand correctly, I think you’re mistaken. The compiler already
>> selects overloads based on generic context. If `T: FloatingPoint`, then
>> it’ll choose the `==` with signature ` (T, T) -> Bool`.
>> If `T: Equatable`, then it’ll choose the `==` with signature `> Equatable> (T, T) -> Bool`. No new compiler features are necessary for this
>> specific behavior.
>>
>> Cheers,
>> Jaden Geller
>>
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jaden Geller via swift-evolution
Oh, I definitely overlooked that part. Thanks for that clarification! I had 
assumed the compiler changes were only necessary for allowing circular default 
implementations while still requiring at least one requirement be implemented.

That said, it’s possible to implement something very, very similar without 
compiler changes:
https://gist.github.com/JadenGeller/7566b3b64b5597ee57e8a509f6fc4bb3#file-context-swift-L43
 


Cheers,
Jaden Geller

> On Apr 13, 2017, at 5:58 PM, Xiaodi Wu  wrote:
> 
> Jaden, the proposal literally says that a compiler feature named 
> "@_implements" is necessary for the proposed design to work. You can see WIP 
> for that feature in the apple/swift repo.
> 
> 
> On Thu, Apr 13, 2017 at 19:55 Jaden Geller  > wrote:
> 
>> On Apr 13, 2017, at 5:18 PM, Xiaodi Wu via swift-evolution 
>> > wrote:
>> 
>> Actually, the fact that this behavior cannot even be achieved without 
>> currently non-existent compiler features means that it is not possible to 
>> understand what's truly going on without reading *this document*, after 
>> mastering *both* IEEE floating point *and* Swift 
>> generics/protocols/extensions/static vs. dynamic dispatch. All to use `==` 
>> correctly. Which is to say, most people will simply not even know if they 
>> happen to be using the `==` they did not intend to use.
>> 
> 
> If I understand correctly, I think you’re mistaken. The compiler already 
> selects overloads based on generic context. If `T: FloatingPoint`, then it’ll 
> choose the `==` with signature ` (T, T) -> Bool`. If `T: 
> Equatable`, then it’ll choose the `==` with signature ` (T, T) 
> -> Bool`. No new compiler features are necessary for this specific behavior.
> 
> Cheers,
> Jaden Geller

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


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 13, 2017, at 17:51, Jonathan Hull via swift-evolution 
>  wrote:
> 
> I think “vastly” is vastly overstating it, especially since they are not 
> customization points… merely aliases.  There is nothing else those operators 
> could do without causing confusion.  Swift favors clarity, and these 
> operators are much more clear (which I count as a benefit).  Also ‘<=‘ looks 
> like an arrow, which I find very distracting in code, as my eye wants to 
> follow it.
> 
> I do use this myself in application code, but I can’t add it to my framework 
> code without potentially clashing with others (or myself) who have added the 
> same behavior for themselves.  Even though the implementations are exactly 
> the same, it becomes ambiguous which of the (identical) definitions should be 
> used.  Having it in the library would mean that everyone would just use that 
> version (and there is only one reasonable implementation, so it wont limit 
> anyone).
> 
> I really don’t think there is danger of harm here as you seem to be implying. 
> Anyone who sees ‘≤’ will know what it means, even if they aren’t familiar 
> with Swift.  If the implementations point to ‘<=‘, etc… then nothing will get 
> out of sync.  There really isn’t any extra maintenance needed.

Agreed. Although to fair, I'm a huge fan of Unicode operators.

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Xiaodi Wu via swift-evolution
On Thu, Apr 13, 2017 at 7:55 PM, Brent Royal-Gordon 
wrote:

> On Apr 13, 2017, at 4:48 PM, Xiaodi Wu  wrote:
>
> You say "this is the example set by `print`", but I don't think anything
>> else actually *follows* that example. No other I/O operation in Swift
>> behaves this way.
>>
>
> To be more accurate, it's not `print` that specifies this behavior, but
> rather the standard output stream's implementation of
> `TextOutputStream.write(_:)`. Swift *explicitly* leaves this choice up to
> the TextOutputStream-conforming type. That is, the behavior is up to the
> receiver and not the argument of a call to `TextOutputStream.write(_:)`.
>
>
> I feel like I must be misunderstanding what you're trying to say here,
> because I *think* what you're trying to say is that
> `TextOutputStream.write(_:)` is what decides whether to add the terminator,
> which is not only totally wrong (see https://github.com/apple/swift/blob/
> adc54c8a4d13fbebfeb68244bac401ef2528d6d0/stdlib/public/core/
> Print.swift#L260) but doesn't even make any sense since there's a
> terminator parameter on `print` but none on `write(_:)`.
>

Hmm, you're right here with respect to `print()`. It is, however,
explicitly contemplated in the documentation for
`TextOutputStream.write(_:)` that conforming types can also determine
whether or not to append a terminator, and which, inside their
implementation of `write`. The example given in the documentation is:

```
struct ASCIILogger: TextOutputStream {
mutating func write(_ string: String) {
let ascii = string.unicodeScalars.lazy.map { scalar in
scalar == "\n"
  ? "\n"
  : scalar.escaped(asASCII: true)
}
print(ascii.joined(separator: ""), terminator: "")
}
}
```



> --
> Brent Royal-Gordon
> Architechies
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jaden Geller via swift-evolution
> 
> On Apr 13, 2017, at 3:23 PM, John McCall via swift-evolution 
>  wrote:
> 
>> On Apr 13, 2017, at 4:17 PM, Ben Cohen via swift-evolution 
>> > wrote:
>> ComparisonResult Conveniences
>> 
>> There are a few conveniences we could consider providing to make 
>> ComparisonResult more ergonomic to manipulate. Such as:
>> 
>> // A way to combine orderings
>> func ComparisonResult.breakingTiesWith(_ order: () -> ComparisonResult) -> 
>> ComparisonResult
>> 
>> array.sort {
>>   $0.x.compare($0.y)
>>   .breakingTiesWith { $0.y.compare($1.y) }
>>   == .orderedAscending 
>> }
> 
> The really nice thing about compare being an operator is that you can very 
> nicely combine it with an operator here and get a much more light-weight 
> syntax for chained comparisons, e.g.:
> 
> struct MyPoint : Comparable {
>   var x, y, z: Double
>   func compare(_ other: MyPointer) -> ComparisonResult {
> return self.x <=> other.x || self.y <=> other.y || self.z <=> other.z

Wow, this is elegant!

>   }
> }
> 
> as opposed to, I guess,
>   return self.x.compare(other.x).breakingTiesWith { 
> self.y.compare(other.y).breakingTiesWith { self.z.compare(other.z) } }
> 
> But this is mostly useful for defining custom comparisons, so perhaps it's 
> not worth having to paint a bikeshed for <=> and whatever the combining 
> operator is.

For the record, I would strongly prefer `<=>` to an instance `compare` method. 
That said, I’d also prefer a static `compare` function to the asymmetric 
instance method if the spelling `compare` were absolutely desired.

It’s probably worth noting somewhere that an instance `compare` method performs 
dynamic dispatch on the left-hand argument while a static function (as well as 
the current operators `==` and `<`) perform static dispatch. I realize NSObject 
set a precedent with `isEqual:` and `compare:` instance methods, but I’m not 
convinced that’s necessarily the best design. If dynamic dispatch is desired, 
an implementation can always delegate to such a method.

> 
> Also, in this example:
>> // A way to combine orderings
>> func ComparisonResult.breakingTiesWith(_ order: () -> ComparisonResult) -> 
>> ComparisonResult
>> 
>> array.sort {
>>   $0.x.compare($0.y)
>>   .breakingTiesWith { $0.y.compare($1.y) }
>>   == .orderedAscending 
>> }
> Requiring this last "== .orderedAscending" seems like a tragic failure of 
> ergonomics.  I understand that sorting doesn't actually require a tri-valued 
> comparison, but is it really worth maintaining two currencies of comparison 
> result over that?  Are there any types that can answer '<' substantially more 
> efficiently than they can answer 'compare'?  And I assume this is related to 
> why you've kept < in the protocol.

I would strongly support replacing (T, T) -> Bool with (T, T) -> 
ComparisonResult variants.

The areInIncreasingOrder variant is confusing at the call-site since the 
definition must be consulted to determine which order the comparison expects.
The areInIncreasingOrder implementation is very dirty when an == result is 
desired. This is especially bad if we expect other authors to mirror this API:
if !areInIncreasingOrder(a, b) && !areInIncreasingOrder(b, a) {
  // equal!
}
Not only is this unintuitive, but it is also less performant in many cases.

> 
> John.
> ___
> 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] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
Jaden, the proposal literally says that a compiler feature named
"@_implements" is necessary for the proposed design to work. You can see
WIP for that feature in the apple/swift repo.


On Thu, Apr 13, 2017 at 19:55 Jaden Geller  wrote:

>
> On Apr 13, 2017, at 5:18 PM, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Actually, the fact that this behavior cannot even be achieved without
> currently non-existent compiler features means that it is not possible to
> understand what's truly going on without reading *this document*, after
> mastering *both* IEEE floating point *and* Swift
> generics/protocols/extensions/static vs. dynamic dispatch. All to use `==`
> correctly. Which is to say, most people will simply not even know if they
> happen to be using the `==` they did not intend to use.
>
>
> If I understand correctly, I think you’re mistaken. The compiler already
> selects overloads based on generic context. If `T: FloatingPoint`, then
> it’ll choose the `==` with signature ` (T, T) -> Bool`.
> If `T: Equatable`, then it’ll choose the `==` with signature ` Equatable> (T, T) -> Bool`. No new compiler features are necessary for this
> specific behavior.
>
> Cheers,
> Jaden Geller
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Paweł Wojtkowiak via swift-evolution
I think the subscript index should not be optional - you want 2nd array 
element, 3rd, etc., not a "nil" element - this makes no sense to me. Also it 
feels like some strange optional behavior compared to the normal usage, so -1 
from me on this idea.

I think that there can be situations where you'd like to have an optional value 
from array, e.g. Checking for index of some element before then increasing it 
by one to get the next one. It would be more convenient and look more clearer 
to have one optional binding in if/guard than checking against the count and 
then handling the element. It also feels natural - there either can be an 
element at given subscript, or there might not be - the first thing it brings 
to mind is optionals, also it feels familiar from dictionaries.

I think we should preserve the unsafe version for performance reasons but allow 
some optional access too, so it feels more natural when reading the code. I saw 
several implementations on stack overflow and the one with "safe:" argument 
name seemed quite popular. I think it would add complexity to the language to 
add another syntax/keyword/strange use cases (like optional index), so I'd stay 
with the argument label. Maybe it's not perfectly pretty, but doesn't harm the 
language in any way and its intentions are clear.

This is of course something everyone could write in their own extension, but I 
think adding it to the standard lib would make me happy. I already had some 
cases where I'd like to use it, not sure about others, but this is still up to 
the discussion.

Wysłane z iPhone'a

Dnia 13.04.2017 o godz. 18:18 David Sweeris  napisał(a):

> 
>> On Apr 13, 2017, at 08:53, Josh Parmenter  wrote:
>> 
>> This seems inconsistent to me. 2 is 2... 2 itself is not optional. You 
>> wouldn't expect 2 to be unwrapped.
> 
> Correct. I think the idea was that "2?" would get converted to an 
> `Optional`, which would then call a subscript that took an `Index?` 
> instead of `Index`. The trailing "?" doesn't do that, but for some reason I 
> thought it might.
> 
> IMHO, the semantics are clear(ish) in context, but it feels slightly odd for 
> "?" to have two opposite behaviors depending on whether the argument is or 
> isn't an Optional.
> 
> In any case, given that we're discussing a "safe subscript", we need a way to 
> differentiate the safe subscript from the unsafe subscript. The only two ways 
> to do that are to either add an argument label or change the argument type, 
> and IMHO the best alternate argument type is `Index?`, since it's pretty 
> light-weight, already part of the stdlib, and already familiar to Swift 
> developers.
> 
> Someone already said it was a bad idea, though, so I'm rethinking my support.
> 
> - Dave Sweeris 
> 
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Brent Royal-Gordon via swift-evolution
> On Apr 13, 2017, at 4:48 PM, Xiaodi Wu  wrote:
> 
> You say "this is the example set by `print`", but I don't think anything else 
> actually *follows* that example. No other I/O operation in Swift behaves this 
> way.
> 
> To be more accurate, it's not `print` that specifies this behavior, but 
> rather the standard output stream's implementation of 
> `TextOutputStream.write(_:)`. Swift *explicitly* leaves this choice up to the 
> TextOutputStream-conforming type. That is, the behavior is up to the receiver 
> and not the argument of a call to `TextOutputStream.write(_:)`.

I feel like I must be misunderstanding what you're trying to say here, because 
I *think* what you're trying to say is that `TextOutputStream.write(_:)` is 
what decides whether to add the terminator, which is not only totally wrong 
(see 
https://github.com/apple/swift/blob/adc54c8a4d13fbebfeb68244bac401ef2528d6d0/stdlib/public/core/Print.swift#L260)
 but doesn't even make any sense since there's a terminator parameter on 
`print` but none on `write(_:)`.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jaden Geller via swift-evolution

> On Apr 13, 2017, at 5:18 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> Actually, the fact that this behavior cannot even be achieved without 
> currently non-existent compiler features means that it is not possible to 
> understand what's truly going on without reading *this document*, after 
> mastering *both* IEEE floating point *and* Swift 
> generics/protocols/extensions/static vs. dynamic dispatch. All to use `==` 
> correctly. Which is to say, most people will simply not even know if they 
> happen to be using the `==` they did not intend to use.
> 

If I understand correctly, I think you’re mistaken. The compiler already 
selects overloads based on generic context. If `T: FloatingPoint`, then it’ll 
choose the `==` with signature ` (T, T) -> Bool`. If `T: 
Equatable`, then it’ll choose the `==` with signature ` (T, T) -> 
Bool`. No new compiler features are necessary for this specific behavior.

Cheers,
Jaden Geller___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jonathan Hull via swift-evolution
I think “vastly” is vastly overstating it, especially since they are not 
customization points… merely aliases.  There is nothing else those operators 
could do without causing confusion.  Swift favors clarity, and these operators 
are much more clear (which I count as a benefit).  Also ‘<=‘ looks like an 
arrow, which I find very distracting in code, as my eye wants to follow it.

I do use this myself in application code, but I can’t add it to my framework 
code without potentially clashing with others (or myself) who have added the 
same behavior for themselves.  Even though the implementations are exactly the 
same, it becomes ambiguous which of the (identical) definitions should be used. 
 Having it in the library would mean that everyone would just use that version 
(and there is only one reasonable implementation, so it wont limit anyone).

I really don’t think there is danger of harm here as you seem to be implying. 
Anyone who sees ‘≤’ will know what it means, even if they aren’t familiar with 
Swift.  If the implementations point to ‘<=‘, etc… then nothing will get out of 
sync.  There really isn’t any extra maintenance needed.

Thanks,
Jon

> On Apr 13, 2017, at 5:03 PM, Xiaodi Wu  wrote:
> 
> On Thu, Apr 13, 2017 at 7:02 PM, Jonathan Hull via swift-evolution 
> > wrote:
> This is a sugar request, but if we are rearranging these things anyway, can 
> we *please* add the ‘≤’, ‘≥’, and ‘≠’ operators to comparable.  I know they 
> would do the same thing as ‘<=‘, ‘>=‘, and ‘!=‘, but they can’t really be 
> used for anything else without being confusing (because they literally have 
> that meaning in mathematics), and they make my code so much more readable.
> 
> This is vastly increasing API surface area for every user of Swift for 
> literally no functionality. Why isn't it sufficient that Swift allows you to 
> do this for yourself without restriction?
>  
> 
> Thanks,
> Jon
> 
>  
>> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution 
>> > wrote:
>> 
>> Online copy here:
>> 
>> https://github.com/airspeedswift/swift-evolution/blob/fa007138a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md
>>  
>> 
> 
> ___
> 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] [pitch] Comparison Reform

2017-04-13 Thread Guillaume Lessard via swift-evolution

> On Apr 13, 2017, at 18:18, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> `compare(_:)` does not merit a term-of-art exception when the Swift name is 
> clearly `compared(to:)`.

No; in full grammatical pedanticity it should be compared(with:).
“compare to” is for dissimilar things.
“compare with” is for similar things.
(I’m not claiming that anyone cares, and I may have a traditional 
interpretation.)


If the whole thing remains couched in terms of comparison, I prefer the 
function to be named compare(_:), because it’s such an everyday term. No one 
expects this action to possibly have a side effect.

Cheers,
Guillaume Lessard

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


Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Xiaodi Wu via swift-evolution
A proposal for lenient subscripts has already been written, and a PR has
been created on the swift-evolution repo and it has been closed for not
being in scope. When it is in scope, it can be considered again. But in the
meantime, the topic has been visited so many times that it's extremely
unlikely for anything previously unsaid to be newly discovered at this
point.


On Thu, Apr 13, 2017 at 7:11 PM, David Sweeris via swift-evolution <
swift-evolution@swift.org> wrote:

>
> > On Apr 13, 2017, at 15:01, Tony Allevato 
> wrote:
> >
> > My 2 cents: Giving users checked subscripts for arrays will do more harm
> than good for novice programmers—they're going to do the wrong thing with
> them.
>
> I'm torn... On the one hand, I see the logic in this. On the other hand, I
> suspect many developers will end up writing such a function anyway
> (regardless of whether it's a good idea), and it'd be nice if there was a
> standard spelling.
>
> I realize this is not a convincing argument; I'm just thinking out loud a
> bit...
>
> Maybe I'll start a "StdBadIdeasLib" project, for all the ideas that could
> be implemented straightforwardly on top of the existing stdlib, but get
> rejected because they're bad ideas... Come to think of it, that's probably
> a bad idea itself (at least it'd be a well-named library, though).
>
> - 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] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
Getting this sorted out is definitely a worthwhile effort. I do have
thoughts about this proposal:

I continue to have reservations about an identical spelling (e.g. `==`)
giving two different answers with the same values of the same type,
depending on the generic context. It is a very *clever* design, but it is
also a very *subtle* behavior that I can see leading to much confusion and
befuddlement for any user who is not well versed *both* in the intricacies
of IEEE floating point *and* in the intricacies of Swift.

Actually, the fact that this behavior cannot even be achieved without
currently non-existent compiler features means that it is not possible to
understand what's truly going on without reading *this document*, after
mastering *both* IEEE floating point *and* Swift
generics/protocols/extensions/static vs. dynamic dispatch. All to use `==`
correctly. Which is to say, most people will simply not even know if they
happen to be using the `==` they did not intend to use.

I think consideration should be given to a design that achieves a
user-facing but not onerous differentiation between level 1 and level 2
equality. However, the only one I can think of is essentially a different
shade of the `PartiallyComparable` alternative already outlined in the
document. Yet I cannot help but think that the rejected alternative may be
advantageous in one key aspect. `FloatingPoint` comparison is in a sense
"less refined" (not exactly precise language, I know) than the level 2
ordering proposed here, at least in the sense that the latter offers more
semantic guarantees about the relationships between comparison operators.
It's weird that the less refined `FloatingPoint` refines the more refined
`Comparable`, and I think the acrobatics with compiler support illustrate
how the design is actively working against Swift's overarching direction.

Anyway, so much for that about the design overall.

As for nitpicking details, I agree with others and think it's a poor
precedent to say that we're going to use an Obj-C name because it's not
clearly worse than the obvious Swift API guideline-compliant name. When
that's the case, it seems to me that the whole point of having Swift API
naming guidelines and making that huge migration from Swift 2 to 3 was so
that going forward we could name things consistently using one consensus
style. `compare(_:)` does not merit a term-of-art exception when the Swift
name is clearly `compared(to:)`.


On Thu, Apr 13, 2017 at 3:17 PM, Ben Cohen via swift-evolution <
swift-evolution@swift.org> wrote:

>
> Hi swift evolution,
>
> Here’s another pitch, for The Propoosal Formerly Known As Spaceship.
> Comparison Reform
>
>- Proposal: SE-
>- Authors: Robert Widmann , Jaden Geller
>, Harlan Haskins
>, Alexis Beingessner
>, Ben Cohen
>
>- Status: *Awaiting review*
>- Review manager: TBD
>
> Introduction
>
> This proposal is for changes that we believe should be made to the
> existing comparison system by:
>
>- Making FloatingPoint comparison context sensitive, so that its
>Comparable conformance provides a proper total ordering.
>- Introducing a new ternary-valued compare(_ other: Self) ->
>ComparisonResult method.
>- Removing unnecessary customization points from Comparable.
>
> Motivation
>
> The motivation comes from several independent points:
>
> 1: The standard comparison operators have an intuitive meaning to
> programmers. Swift encourages encoding that in an implementation of
> Comparable that respects the rules of a total order
> . The standard library takes
> advantage of these rules to provide consistent implementations for sorting
> and searching generic collections of Comparable types.
>
> Not all types behave so well in this framework, unfortunately. There are
> cases where the semantics of a total order cannot apply while still
> maintaining the traditional definition of “comparison” for these types.
> Take, for example, sorting an array of Floats. Today, Float’s instance of
> Comparable follows IEEE-754 and returns false for all comparisons of NaN.
> In order to sort this array, NaN s are considered outside the domain of <,
> and the order of a sorted array containing them is unspecified. Similarly,
> a Dictionary keyed off floats can leak entries and memory.
>
> 2: Generic algorithms in the Swift Standard Library that make use of the
> current Comparable protocol may have to make extra comparisons to
> determine the ordering of values when <, ==, and > should have different
> behaviours. Having a central operation to return complete ordering
> information should provide a speedup for these operations.
>
> 3: The existing comparison operators don’t “generalize” well. There’s no
> clean way to add a third or fourth argument to < to 

Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 13, 2017, at 15:01, Tony Allevato  wrote:
> 
> My 2 cents: Giving users checked subscripts for arrays will do more harm than 
> good for novice programmers—they're going to do the wrong thing with them.

I'm torn... On the one hand, I see the logic in this. On the other hand, I 
suspect many developers will end up writing such a function anyway (regardless 
of whether it's a good idea), and it'd be nice if there was a standard spelling.

I realize this is not a convincing argument; I'm just thinking out loud a bit...

Maybe I'll start a "StdBadIdeasLib" project, for all the ideas that could be 
implemented straightforwardly on top of the existing stdlib, but get rejected 
because they're bad ideas... Come to think of it, that's probably a bad idea 
itself (at least it'd be a well-named library, though).

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


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Xiaodi Wu via swift-evolution
On Thu, Apr 13, 2017 at 7:02 PM, Jonathan Hull via swift-evolution <
swift-evolution@swift.org> wrote:

> This is a sugar request, but if we are rearranging these things anyway,
> can we *please* add the ‘≤’, ‘≥’, and ‘≠’ operators to comparable.  I know
> they would do the same thing as ‘<=‘, ‘>=‘, and ‘!=‘, but they can’t really
> be used for anything else without being confusing (because they literally
> have that meaning in mathematics), and they make my code so much more
> readable.
>

This is vastly increasing API surface area for every user of Swift for
literally no functionality. Why isn't it sufficient that Swift allows you
to do this for yourself without restriction?


>
> Thanks,
> Jon
>
>
>
> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Online copy here:
>
> https://github.com/airspeedswift/swift-evolution/blob/
> fa007138a54895e94d22e053122ca24ffa0b2eeb/proposals/-
> ComparisonReform.md
>
>
>
> ___
> 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] [pitch] Comparison Reform

2017-04-13 Thread Jonathan Hull via swift-evolution
This is a sugar request, but if we are rearranging these things anyway, can we 
*please* add the ‘≤’, ‘≥’, and ‘≠’ operators to comparable.  I know they would 
do the same thing as ‘<=‘, ‘>=‘, and ‘!=‘, but they can’t really be used for 
anything else without being confusing (because they literally have that meaning 
in mathematics), and they make my code so much more readable.

Thanks,
Jon

 
> On Apr 13, 2017, at 1:24 PM, Ben Cohen via swift-evolution 
>  wrote:
> 
> Online copy here:
> 
> https://github.com/airspeedswift/swift-evolution/blob/fa007138a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md
>  
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jonathan Hull via swift-evolution

> On Apr 13, 2017, at 2:42 PM, David Hart via swift-evolution 
>  wrote:
> 
> It feels weird to me to jump through all these hoops just for backwards 
> compatibility. Seeing how even big projects might only have several 
> Comparable conformances, wouldn’t it be worth removing the default 
> implementation of compare and removing < from Comparable?

It isn’t just backwards compatibility.  As someone who has worked with both 
forms of comparable, I can say that just implementing ‘<‘ is much easier, 
especially when you are just chaining results of comparing components.  In one 
case I can just use ‘||' and ‘&&’, the other may require pattern matching in a 
switch. (I usually still have to implement ‘==‘ anyway in both cases, so it 
isn’t a difference between the two).

>> Different Names For compare and ComparisonResult
>> 
>> A few different variants for ComparisonResult and its variants were 
>> considered:
>> 
>> Dropping the ordered part of ComparisonResult’s cases e.g. .ascending
>> Naming of ComparisonResult as SortOrder
>> enum Ordering { case less, equal, greater } (as used by Rust 
>> )
>> Case values of inOrder, same, outOfOrder
>> The choice of case names is non-trivial because the enum shows up in 
>> different contexts where different names makes more sense. Effectively, one 
>> needs to keep in mind that the “default” sort order is ascending to map 
>> between the concept of “before” and “less”.
>> 
>> The before/after naming to provide the most intuitive model for custom sorts 
>> – referring to ascending or less is confusing when trying to implement a 
>> descending ordering. Similarly the inOrder/outOfOrder naming was too 
>> indirect – it’s more natural to just say where to put the element. If the 
>> enum should focus on the sorting case, calling it SortOrder would help to 
>> emphasize this fact.
>> 
> Can you give an example where ascending/descending/equal can be confusing?

Agreed.  Ascending & Descending imply an ordering to me.  I don’t see how the 
extra ‘ordered’ clarifies anything…

>> This proposal elects to leave the existing Foundation name in-place. The 
>> primary motivation for this is that use of the compare function will be 
>> relatively rare. It is expected that in most cases users will continue to 
>> make use of == or <, returning boolean values (the main exception to this 
>> will be in use of the parameterized String comparisons). As such, the source 
>> compatibility consequences of introducing naming changes to an existing type 
>> seems of insufficient benefit.
>> 
>> The method compare(_:) does not fully comport with the API naming 
>> guidelines. However, it is firmly established with current usage in 
>> Objective-C APIs, will be fairly rarely seen/used (users will usually prefer 
>> <, == etc), and alternatives considered, for example compared(to:), were not 
>> a significant improvement.
>> 
> Uses of the compare function might be rare, but I still think it should 
> follow the API naming guidelines. I don’t think that Objective-C conventions 
> are a strong enough argument to warrant breaking those guidelines, especially 
> in the Standard Library.

Agreed.

Thanks,
Jon

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Xiaodi Wu via swift-evolution
On Thu, Apr 13, 2017 at 4:03 AM, Brent Royal-Gordon 
wrote:

> On Apr 12, 2017, at 5:39 PM, Xiaodi Wu  wrote:
>
> On Wed, Apr 12, 2017 at 5:20 PM, Brent Royal-Gordon <
> br...@architechies.com> wrote:
>
>> Wow, maybe I shouldn't have slept.
>>
>> Okay, let's deal with trailing newline first. I'm *very* confident that
>> trailing newlines should be kept by default. This opinion comes from lots
>> of practical experience with multiline string features in other languages.
>> In practice, if you're generating files in a line-oriented way, you're
>> usually generating them a line at a time. It's pretty rare that you want to
>> generate half a line and then add more to it in another statement; it's
>> more likely you'll interpolate the data. I'm not saying it doesn't happen,
>> of course, but it happens a lot less often than you would think just
>> sitting by the fire, drinking whiskey and musing over strings.
>>
>> I know that, if you're pushing for this feature, it's not satisfying to
>> have the answer be "trust me, it's not what you want". But trust me, it's
>> not what you want.
>>
>
> This is not a very good argument. If you are generating files in a
> line-oriented way, it is the function _emitting_ the string that handles
> the line-orientedness, not the string itself. That is the example set by
> `print()`:
>
> ```
> print("Hello, world!") // Emits "Hello, world!\n"
> ```
>
>
> You say "this is the example set by `print`", but I don't think anything
> else actually *follows* that example. No other I/O operation in Swift
> behaves this way.
>

To be more accurate, it's not `print` that specifies this behavior, but
rather the standard output stream's implementation of
`TextOutputStream.write(_:)`. Swift *explicitly* leaves this choice up to
the TextOutputStream-conforming type. That is, the behavior is up to the
receiver and not the argument of a call to `TextOutputStream.write(_:)`.

The underlying `TextOutputStream.write(_:)` doesn't; the I/O in Foundation
> doesn't; file descriptor I/O doesn't.
>

And this goes to my point: there is line-oriented I/O, and there is
non-line-oriented I/O. After all, why would I/O operations designed to
write arbitrary bytes emit trailing newlines by default? It is the I/O
operation that determines whether trailing newlines are implied or not,
*not* the string.

Concatenation certainly doesn't; nor does anything else you might do to
> assemble several multiline string literals into a whole.
>

And this goes to my other point: it *shouldn't*, because there is nothing
about concatenation that is specifically "line-oriented." I am not aware of
any language that concatenates with `+` which infers a default separator.
Anyone who has ever used `+` has *always* appended their own separator.
That is the user expectation, not what you show below.

So I think `print()` is the exception here, not the rule.
>
> In my opinion, modulo the "newline after leading delimiter" question, if
> code like this example:
>
> var xml = """
> 
> 
> """
> for (id, author, title, genre, price) in bookTuples {
> xml += """
> 
> \(author)
> \(title)
> \(genre)
> \(price)
> 
> """
> }
> xml += """
> 
> """
>
> Doesn't assemble the kind of string that it's blatantly obvious the user
> is trying to assemble, I think the syntax has failed.
>

First, let's be clear that this is an argument against your proposed
no-newline-stripping-anywhere rule, so clearly this is not the motivating
use case for that proposed design. I see you've moved away from it.

Second, this is a circular argument, where you are asserting that your
proposed no-trailing-newline-stripping is the only blatantly obvious
meaning because it is blatantly obvious. On the contrary, it is not at all
clear to me that the user obviously wants a newline, not any more so than
the following, which clearly does not and should not insert newlines:

```
var xml = ""
xml += ""

for (id, _, _, _, _) in bookTuples {
  xml += "Book ID: \(id)"
}

xml += ""
```

To me, the only blatantly obvious behavior is that if you're going to want
a separator and you're using `+` or `+=` for string concatenation, you
concatenate the separator yourself. Why would that change just because
there's multiline string syntax? The only thing that multiline string
syntax should _maybe_ suggest to the reader is that there's a decent chance
that there's a newline somewhere in the string, *not* that there's a decent
chance that the string ends with one.


`print()` is the outlier. It's an important enough outlier that we should
> probably help the user notice when they're about to get it wrong, but an
> outlier it is.
>
> --
> Brent Royal-Gordon
> Architechies
>
>
___
swift-evolution mailing list
swift-evolution@swift.org

Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Jonathan Hull via swift-evolution
I still like the ordering of floats defined in this proposal best (and think we 
should use it), but I imagine that there are other types which are almost (but 
not quite) comparable as well. Would there be any utility in having a 
‘PartialComparable’ protocol that defined a single method:

func compare(_:)->ComparisonResult?

That is, it is just like our compare, but it returns nil if two values can’t be 
meaningfully compared.  It would force you to deal with the cases where the 
comparison didn’t make sense, and handle it in a reasonable way in your code. 
(e.g. filtering those values out, or sticking them at the end).

You can think of it as failable compare...

Thanks,
Jon


> On Apr 13, 2017, at 1:17 PM, Ben Cohen via swift-evolution 
>  wrote:
> PartialComparable
> 
> PartialComparable would essentially just be Comparable without any stated 
> ordering requirements, that Comparable extends to provide ordering 
> requirements. This would be a protocol that standard IEEE comparison could 
> satisfy, but in the absence of total ordering requirements, PartialComparable 
> is effectively useless. Either everyone would consume PartialComparable (to 
> accept floats) or Comparable (to have reasonable behaviour).
> 
> The Rust community adopted this strategy to little benefit. The Rust libs 
> team has frequently considered removing the distinction, but hasn’t because 
> doing it backwards compatibly would be complicated. Also because merging the 
> two would just lead to the problems Swift has today.
> 

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


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Matthew Johnson via swift-evolution

> On Apr 13, 2017, at 5:18 PM, Remy Demarest (Psy) via swift-evolution 
>  wrote:
> 
> 
> Remy Demarest
> remy.demar...@gmail.com 
> 
> 
> 
>> Le 13 avr. 2017 à 13:17, Ben Cohen via swift-evolution 
>> > a écrit :
>> 
>> 
>> Hi swift evolution,
>> 
>> Here’s another pitch, for The Propoosal Formerly Known As Spaceship.
>> Comparison Reform
>> 
>> Proposal: SE- 
>> 
>> Authors: Robert Widmann , Jaden Geller 
>> , Harlan Haskins 
>> , Alexis Beingessner 
>> , Ben Cohen 
>> Status: Awaiting review
>> Review manager: TBD
>> Introduction
>> 
>> This proposal is for changes that we believe should be made to the existing 
>> comparison system by:
>> 
>> Making FloatingPoint comparison context sensitive, so that its Comparable 
>> conformance provides a proper total ordering.
>> Introducing a new ternary-valued compare(_ other: Self) -> ComparisonResult 
>> method.
>> Removing unnecessary customization points from Comparable.
>> Motivation
>> 
>> The motivation comes from several independent points:
>> 
>> 1: The standard comparison operators have an intuitive meaning to 
>> programmers. Swift encourages encoding that in an implementation of 
>> Comparable that respects the rules of a total order 
>> . The standard library takes 
>> advantage of these rules to provide consistent implementations for sorting 
>> and searching generic collections of Comparable types.
>> 
>> Not all types behave so well in this framework, unfortunately. There are 
>> cases where the semantics of a total order cannot apply while still 
>> maintaining the traditional definition of “comparison” for these types. 
>> Take, for example, sorting an array of Floats. Today, Float’s instance of 
>> Comparable follows IEEE-754 and returns false for all comparisons of NaN. In 
>> order to sort this array, NaN s are considered outside the domain of <, and 
>> the order of a sorted array containing them is unspecified. Similarly, a 
>> Dictionary keyed off floats can leak entries and memory.
>> 
>> 2: Generic algorithms in the Swift Standard Library that make use of the 
>> current Comparable protocol may have to make extra comparisons to determine 
>> the ordering of values when <, ==, and > should have different behaviours. 
>> Having a central operation to return complete ordering information should 
>> provide a speedup for these operations.
>> 
>> 3: The existing comparison operators don’t “generalize” well. There’s no 
>> clean way to add a third or fourth argument to < to ask for non-default 
>> semantics. An example where this would be desirable would be specifying the 
>> locale or case-sensitivity when comparing Strings.
>> 
>> 4: Comparable is over-engineered in the customization points it provides: to 
>> our knowledge, there’s no good reason to ever override >=, >, or <=. Each 
>> customization point bloats vtables and mandates additional dynamic dispatch.
>> 
>> 5: When quickly writing a Comparable type, it is easier to implement a 
>> single ternary statement than to separately implement == and <.
>> 
>> Proposed solution
>> 
>> ComparisonResult
>> 
>> Foundation’s ComparisonResult type will be mapped into Swift as
>> 
>> @objc public enum ComparisonResult : Int {
>>   case orderedAscending = -1
>>   case orderedSame = 0
>>   case orderedDescending = 1
>> }
>> Comparable
>> 
>> Comparable will be changed to have a new ternary comparison method: 
>> compare(_ other: Self) -> ComparisonResult. x.compare(y) specifies where to 
>> place x relative to y. So if it yields .orderedAscending, then x comes 
>> before y. This will be considered the new “main” dispatch point of 
>> Comparable that implementors should provide.
>> 
>> Most code will continue to use < or ==, as it will be optimal for their 
>> purposes. However code that needs to make a three-way branch on comparison 
>> can use the potentially more efficient compare. Note that compare is only 
>> expected to be more efficient in this specific case. If a two-way branch is 
>> all that’s being done, < will be more efficient in many cases (if only 
>> because it’s easier for the optimizer).
>> 
>> For backwards compatibility reasons, compare will have a default 
>> implementation defined in terms of <, but to enable only using compare, < 
>> and == will also have default implementations in terms of compare.
>> 
>> The compiler will verify that either compare, or < and ==, are provided by 
>> every type that claims to conform to Comparable. This will be done in some 
>> unspecified way unavailable outside the standard library (it can be made 
>> available to in the future, but that’s an unnecessary distraction for this 
>> proposal).
>> 
> 
> Is it really necessary? 

Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread John McCall via swift-evolution
> On Apr 13, 2017, at 4:17 PM, Ben Cohen via swift-evolution 
>  wrote:
> ComparisonResult Conveniences
> 
> There are a few conveniences we could consider providing to make 
> ComparisonResult more ergonomic to manipulate. Such as:
> 
> // A way to combine orderings
> func ComparisonResult.breakingTiesWith(_ order: () -> ComparisonResult) -> 
> ComparisonResult
> 
> array.sort {
>   $0.x.compare($0.y)
>   .breakingTiesWith { $0.y.compare($1.y) }
>   == .orderedAscending 
> }

The really nice thing about compare being an operator is that you can very 
nicely combine it with an operator here and get a much more light-weight syntax 
for chained comparisons, e.g.:

struct MyPoint : Comparable {
  var x, y, z: Double
  func compare(_ other: MyPointer) -> ComparisonResult {
return self.x <=> other.x || self.y <=> other.y || self.z <=> other.z
  }
}

as opposed to, I guess,
  return self.x.compare(other.x).breakingTiesWith { 
self.y.compare(other.y).breakingTiesWith { self.z.compare(other.z) } }

But this is mostly useful for defining custom comparisons, so perhaps it's not 
worth having to paint a bikeshed for <=> and whatever the combining operator is.

Also, in this example:
> // A way to combine orderings
> func ComparisonResult.breakingTiesWith(_ order: () -> ComparisonResult) -> 
> ComparisonResult
> 
> array.sort {
>   $0.x.compare($0.y)
>   .breakingTiesWith { $0.y.compare($1.y) }
>   == .orderedAscending 
> }
Requiring this last "== .orderedAscending" seems like a tragic failure of 
ergonomics.  I understand that sorting doesn't actually require a tri-valued 
comparison, but is it really worth maintaining two currencies of comparison 
result over that?  Are there any types that can answer '<' substantially more 
efficiently than they can answer 'compare'?  And I assume this is related to 
why you've kept < in the protocol.

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


Re: [swift-evolution] Proposal: Split extensions into implementing methods and adding static functions Was: [swift-evolution-announce] [Review] SE-0164: Remove final support in protocol extensions

2017-04-13 Thread Brent Royal-Gordon via swift-evolution
> On Apr 13, 2017, at 3:10 PM, Howard Lovatt via swift-evolution 
>  wrote:
> 
> I don't see that retroactive conformance needs to be exportable. If it is 
> exported then you cannot prevent clashes from two modules, this is a known 
> problem in C#. Because of this and other problems with C# extensions, this 
> style of extension were rejected by other language communities (notably Java 
> and Scala). 
> 
> A better alternative for export is a new class that encapsulates the standard 
> type but with added methods for the protocol to be added. This way there is 
> no clash between modules. EG:
> 
> public protocol P {
> func m() -> String
> }
> public class PInt: P {
> var value = 0
> func m() -> String { return "PI.m" }
> }

Howard, this would be very source-breaking and would fail to achieve 
fundamental goals of Swift's protocol design. Removing retroactive conformance 
is no more realistic than removing Objective-C bridging—another feature which 
introduces various ugly edge cases and tricky behaviors but is also 
non-negotiable.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] Proposal: Split extensions into implementing methods and adding static functions Was: [swift-evolution-announce] [Review] SE-0164: Remove final support in protocol extensions

2017-04-13 Thread Howard Lovatt via swift-evolution
I don't see that retroactive conformance needs to be exportable. If it is 
exported then you cannot prevent clashes from two modules, this is a known 
problem in C#. Because of this and other problems with C# extensions, this 
style of extension were rejected by other language communities (notably Java 
and Scala). 

A better alternative for export is a new class that encapsulates the standard 
type but with added methods for the protocol to be added. This way there is no 
clash between modules. EG:

public protocol P {
func m() -> String
}
public class PInt: P {
var value = 0
func m() -> String { return "PI.m" }
}

-- Howard. 

> On 13 Apr 2017, at 10:31 pm, Xiaodi Wu  wrote:
> 
> The retroactive conformance needs to be exportable. If one cannot vend a 
> library that conforms standard library types to new protocols, then that is a 
> non-starter.
> 
> 
>> On Thu, Apr 13, 2017 at 06:07 Howard Lovatt  wrote:
>> @Xiaodi,
>> 
>> You can safely post-hoc add protocols and methods provided that they are 
>> final, do not override, and are not exported from the module. See version 2 
>> of the proposal below. 
>> 
>> -- Howard.
>> 
>> # Proposal: Split extension usage up into implementing methods and adding 
>> methods and protocols post-hoc
>> 
>> Draft 2 (Added support for post-hoc conformance to a protocol - replaced 
>> static final extensions with final extensions)
>> 
>> ## Introduction
>> 
>> Currently extension methods are confusing because they have different 
>> dispatch rules for the same calling syntax. EG:
>> 
>> public protocol P {
>> func mP() -> String
>>  }
>> extension P {
>> func mP() -> String { return "P.mP" }
>> func mE() -> String { return "P.mE" }
>> }
>> struct S: P {
>> func mP() -> String { return "S.mP" }
>> func mE() -> String { return "S.mE" }
>> }
>> let s = S()
>> s.mP() // S.mP as expected
>> s.mE() // S.mE as expected
>> let p: P = s // Note: s now typed as P
>> p.mP() // S.mP as expected
>> p.mE() // P.mE unexpected!
>> 
>> Extension methods can also cause compatibility problems between modules, 
>> consider:
>> 
>> In Module A
>> extension Int: P {
>> func m() -> String { print("A.m") }
>> }
>> 
>> In Module B
>> extension Int: P {
>> func m() -> String { print("B.m") }
>> }
>> 
>> In Module C
>> import A
>> import B // Should this be an error
>> let i = 0
>> i.m() // Should it return A.m or B.m?
>> 
>> This proposal cures the above two problems by separating extension methods 
>> into two seperate use cases: implementations for methods and adding methods 
>> and protocols post-hoc. 
>> 
>> ## Implementing methods
>> 
>> If the extension is in the same file as the protocol/struct/class 
>> declaration then it implements the methods and is dispatched using a Vtable. 
>> EG:
>> 
>> File P.swift
>> protocol/struct/class P {
>> // func m() not declared in type since it is added by the extension, 
>> under this proposal it is an error to include a declaration in a type *and* 
>> in an extension
>> }
>> extension P {
>> func m() { print("P.m") } // m is added to the protocol/struct/class 
>> declaration
>> }
>> 
>> Same or other file
>> struct S: P {
>> override func m() { print("S.m") } // Note override required because 
>> m already has an implementation from the extension
>> }
>> let p: P = S() // Note typed as P
>> p.m() // Now prints S.m as expected 
>> 
>> Extensions in the same file as the declaration can have any access, can be 
>> final, and can have where clauses and provide inheritable implementations. 
>> 
>> In a protocol at present there is a difference in behaviour between a 
>> protocol that declares a method that is then implemented in an extension and 
>> a protocol that just has the method implemented in an extension and no 
>> declaration. This situation only applies to protocols, for structs and 
>> classes you cannot declare in type and implement in extensions. The proposal 
>> unifies the behaviour of protocol/struct/class with extensions and prevents 
>> the error of a minor typo between the protocol and extension adding two 
>> methods instead of generating an error.
>> 
>> The implementation needed to achieve this is that a value instance typed as 
>> a protocol is copied onto the heap, a pointer to its Vtable added, and it is 
>> passed as a pointer. IE it becomes a class instance. No change needed for a 
>> class instance typed as a protocol. 
>> 
>> ## Post-hoc adding protocols and methods
>> 
>> A new type of extension is proposed, a "final extension", which can be 
>> either in or outside the file in which the protocol/struct/class declaration 
>> is in. EG:
>> 
>> protocol P2 {
>> func m2P()
>> }
>> final extension S: P2 { // Note extension marked final
>>   

Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Tony Allevato via swift-evolution
On Thu, Apr 13, 2017 at 2:55 PM Brent Royal-Gordon via swift-evolution <
swift-evolution@swift.org> wrote:

> On Apr 13, 2017, at 9:18 AM, David Sweeris via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> In any case, given that we're discussing a "safe subscript", we need a way
> to differentiate the safe subscript from the unsafe subscript. The only two
> ways to do that are to either add an argument label or change the argument
> type, and IMHO the best alternate argument type is `Index?`, since it's
> pretty light-weight, already part of the stdlib, and already familiar to
> Swift developers.
>
>
> Compiler and syntax issues aside, the real issue with using `Int?` as the
> type is this: If you take `Int?` as a subscript type, then someone can say
> `foos[nil]`. What are you going to do about that? It's obviously incorrect,
> so you really ought to fail a precondition, but that means you've opened a
> "safety" hole as bad as the original one, purely to get a nice syntax.
>
> So, I think if you're going to do this, you need an argument label. The
> question then is, what label should we use?
>
> The most common choice is `safe`, but "safe" has a specific meaning in the
> Swift compiler and standard library (i.e. memory safety), and we shouldn't
> muddy that. Instead I'll nominate `checking`, which in context reads like:
>
> if let foo = foos[checking: i] { … }
>
> (But keep in mind that you shouldn't use the checking subscript in
> `tableView(_:numberOfRowsInSection:)` or any of the other table view
> delegate methods. Section and row indices should always be derived from the
> count of the same array you're indexing, so it should never be possible to
> receive an invalid section or row index in a table view delegate/data
> source method. If that happens, the only possible cause is programmer
> error, and the correct behavior when Swift code detects programmer error is
> to fail a precondition and trap.
>
> I'd actually say the #1 reason not to add this feature is that a lot of
> developers don't seem to understand this, and they're likely to use the
> feature to make their code try to continue in the face of programmer error
> instead of trapping like it properly should. A program in an inconsistent
> state is dangerous; best to stop it quickly before it does some damage.)
>

Since you already beat me to the rest of what I was typing about optionals
as the index, I'll +1 the sentiment in this last part :)

The need for checking subscripts should be *extremely rare*, which is why I
think most of the proposals in this area flounder.

An out-of-bound index is a *logic error* in the program. In most cases
(like the tableView example cited above), the indices you use elsewhere to
access elements of those arrays should already be guaranteed by other
invariants in your program. If they're not, and if you think you need to
use a checked subscript, then you're just putting some tape over the
problem instead of fixing a serious underlying bug.

Most of the time you're working with arrays, you should be using for-in
loops (where indexes don't matter) or the Collection index APIs (which will
guarantee that you're getting valid indexes without worrying about that
fact that they're numbers underneath).

It should be quite rare that you're accessing elements at arbitrary numeric
indexes within an array. I imagine most such cases come from user
input—either a number the user has entered, or them clicking on a
particular location on a view and then you translate that pixel location
into an array index and look something up that way. In those cases, you
should probably just do the bounds checking yourself.

My 2 cents: Giving users checked subscripts for arrays will do more harm
than good for novice programmers—they're going to do the wrong thing with
them.



> --
> Brent Royal-Gordon
> Architechies
>
> ___
> 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] [Pitch] Adding safety to arrays

2017-04-13 Thread Brent Royal-Gordon via swift-evolution
> On Apr 13, 2017, at 9:18 AM, David Sweeris via swift-evolution 
>  wrote:
> 
> In any case, given that we're discussing a "safe subscript", we need a way to 
> differentiate the safe subscript from the unsafe subscript. The only two ways 
> to do that are to either add an argument label or change the argument type, 
> and IMHO the best alternate argument type is `Index?`, since it's pretty 
> light-weight, already part of the stdlib, and already familiar to Swift 
> developers.


Compiler and syntax issues aside, the real issue with using `Int?` as the type 
is this: If you take `Int?` as a subscript type, then someone can say 
`foos[nil]`. What are you going to do about that? It's obviously incorrect, so 
you really ought to fail a precondition, but that means you've opened a 
"safety" hole as bad as the original one, purely to get a nice syntax.

So, I think if you're going to do this, you need an argument label. The 
question then is, what label should we use?

The most common choice is `safe`, but "safe" has a specific meaning in the 
Swift compiler and standard library (i.e. memory safety), and we shouldn't 
muddy that. Instead I'll nominate `checking`, which in context reads like:

if let foo = foos[checking: i] { … }

(But keep in mind that you shouldn't use the checking subscript in 
`tableView(_:numberOfRowsInSection:)` or any of the other table view delegate 
methods. Section and row indices should always be derived from the count of the 
same array you're indexing, so it should never be possible to receive an 
invalid section or row index in a table view delegate/data source method. If 
that happens, the only possible cause is programmer error, and the correct 
behavior when Swift code detects programmer error is to fail a precondition and 
trap.

I'd actually say the #1 reason not to add this feature is that a lot of 
developers don't seem to understand this, and they're likely to use the feature 
to make their code try to continue in the face of programmer error instead of 
trapping like it properly should. A program in an inconsistent state is 
dangerous; best to stop it quickly before it does some damage.)

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread David Hart via swift-evolution
Looking good. A few comments inline:

> On 13 Apr 2017, at 22:17, Ben Cohen via swift-evolution 
>  wrote:
> 
> 
> Hi swift evolution,
> 
> Here’s another pitch, for The Propoosal Formerly Known As Spaceship.
> Comparison Reform
> 
> Proposal: SE- 
> 
> Authors: Robert Widmann , Jaden Geller 
> , Harlan Haskins 
> , Alexis Beingessner 
> , Ben Cohen 
> Status: Awaiting review
> Review manager: TBD
> Introduction
> 
> This proposal is for changes that we believe should be made to the existing 
> comparison system by:
> 
> Making FloatingPoint comparison context sensitive, so that its Comparable 
> conformance provides a proper total ordering.
> Introducing a new ternary-valued compare(_ other: Self) -> ComparisonResult 
> method.
> Removing unnecessary customization points from Comparable.
> Motivation
> 
> The motivation comes from several independent points:
> 
> 1: The standard comparison operators have an intuitive meaning to 
> programmers. Swift encourages encoding that in an implementation of 
> Comparable that respects the rules of a total order 
> . The standard library takes 
> advantage of these rules to provide consistent implementations for sorting 
> and searching generic collections of Comparable types.
> 
> Not all types behave so well in this framework, unfortunately. There are 
> cases where the semantics of a total order cannot apply while still 
> maintaining the traditional definition of “comparison” for these types. Take, 
> for example, sorting an array of Floats. Today, Float’s instance of 
> Comparable follows IEEE-754 and returns false for all comparisons of NaN. In 
> order to sort this array, NaN s are considered outside the domain of <, and 
> the order of a sorted array containing them is unspecified. Similarly, a 
> Dictionary keyed off floats can leak entries and memory.
> 
> 2: Generic algorithms in the Swift Standard Library that make use of the 
> current Comparable protocol may have to make extra comparisons to determine 
> the ordering of values when <, ==, and > should have different behaviours. 
> Having a central operation to return complete ordering information should 
> provide a speedup for these operations.
> 
> 3: The existing comparison operators don’t “generalize” well. There’s no 
> clean way to add a third or fourth argument to < to ask for non-default 
> semantics. An example where this would be desirable would be specifying the 
> locale or case-sensitivity when comparing Strings.
> 
> 4: Comparable is over-engineered in the customization points it provides: to 
> our knowledge, there’s no good reason to ever override >=, >, or <=. Each 
> customization point bloats vtables and mandates additional dynamic dispatch.
> 
> 5: When quickly writing a Comparable type, it is easier to implement a single 
> ternary statement than to separately implement == and <.
> 
> Proposed solution
> 
> ComparisonResult
> 
> Foundation’s ComparisonResult type will be mapped into Swift as
> 
> @objc public enum ComparisonResult : Int {
>   case orderedAscending = -1
>   case orderedSame = 0
>   case orderedDescending = 1
> }
> Comparable
> 
> Comparable will be changed to have a new ternary comparison method: compare(_ 
> other: Self) -> ComparisonResult. x.compare(y) specifies where to place x 
> relative to y. So if it yields .orderedAscending, then x comes before y. This 
> will be considered the new “main” dispatch point of Comparable that 
> implementors should provide.
> 
> Most code will continue to use < or ==, as it will be optimal for their 
> purposes. However code that needs to make a three-way branch on comparison 
> can use the potentially more efficient compare. Note that compare is only 
> expected to be more efficient in this specific case. If a two-way branch is 
> all that’s being done, < will be more efficient in many cases (if only 
> because it’s easier for the optimizer).
> 
> For backwards compatibility reasons, compare will have a default 
> implementation defined in terms of <, but to enable only using compare, < and 
> == will also have default implementations in terms of compare.
> 
> The compiler will verify that either compare, or < and ==, are provided by 
> every type that claims to conform to Comparable. This will be done in some 
> unspecified way unavailable outside the standard library (it can be made 
> available to in the future, but that’s an unnecessary distraction for this 
> proposal).
> 
It feels weird to me to jump through all these hoops just for backwards 
compatibility. Seeing how even big projects might only have several Comparable 
conformances, wouldn’t it be worth removing the default implementation of 
compare and removing < from Comparable?
> Types that wish to provide comparison “variants” can do so 

Re: [swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Ben Cohen via swift-evolution
Online copy here:

https://github.com/airspeedswift/swift-evolution/blob/fa007138a54895e94d22e053122ca24ffa0b2eeb/proposals/-ComparisonReform.md


> On Apr 13, 2017, at 1:17 PM, Ben Cohen via swift-evolution 
>  wrote:
> 
> 
> Hi swift evolution,
> 
> Here’s another pitch, for The Propoosal Formerly Known As Spaceship.
> Comparison Reform
> 
> Proposal: SE- 
> 
> Authors: Robert Widmann , Jaden Geller 
> , Harlan Haskins 
> , Alexis Beingessner 
> , Ben Cohen 
> Status: Awaiting review
> Review manager: TBD
> Introduction
> 
> This proposal is for changes that we believe should be made to the existing 
> comparison system by:
> 
> Making FloatingPoint comparison context sensitive, so that its Comparable 
> conformance provides a proper total ordering.
> Introducing a new ternary-valued compare(_ other: Self) -> ComparisonResult 
> method.
> Removing unnecessary customization points from Comparable.
> Motivation
> 
> The motivation comes from several independent points:
> 
> 1: The standard comparison operators have an intuitive meaning to 
> programmers. Swift encourages encoding that in an implementation of 
> Comparable that respects the rules of a total order 
> . The standard library takes 
> advantage of these rules to provide consistent implementations for sorting 
> and searching generic collections of Comparable types.
> 
> Not all types behave so well in this framework, unfortunately. There are 
> cases where the semantics of a total order cannot apply while still 
> maintaining the traditional definition of “comparison” for these types. Take, 
> for example, sorting an array of Floats. Today, Float’s instance of 
> Comparable follows IEEE-754 and returns false for all comparisons of NaN. In 
> order to sort this array, NaN s are considered outside the domain of <, and 
> the order of a sorted array containing them is unspecified. Similarly, a 
> Dictionary keyed off floats can leak entries and memory.
> 
> 2: Generic algorithms in the Swift Standard Library that make use of the 
> current Comparable protocol may have to make extra comparisons to determine 
> the ordering of values when <, ==, and > should have different behaviours. 
> Having a central operation to return complete ordering information should 
> provide a speedup for these operations.
> 
> 3: The existing comparison operators don’t “generalize” well. There’s no 
> clean way to add a third or fourth argument to < to ask for non-default 
> semantics. An example where this would be desirable would be specifying the 
> locale or case-sensitivity when comparing Strings.
> 
> 4: Comparable is over-engineered in the customization points it provides: to 
> our knowledge, there’s no good reason to ever override >=, >, or <=. Each 
> customization point bloats vtables and mandates additional dynamic dispatch.
> 
> 5: When quickly writing a Comparable type, it is easier to implement a single 
> ternary statement than to separately implement == and <.
> 
> Proposed solution
> 
> ComparisonResult
> 
> Foundation’s ComparisonResult type will be mapped into Swift as
> 
> @objc public enum ComparisonResult : Int {
>   case orderedAscending = -1
>   case orderedSame = 0
>   case orderedDescending = 1
> }
> Comparable
> 
> Comparable will be changed to have a new ternary comparison method: compare(_ 
> other: Self) -> ComparisonResult. x.compare(y) specifies where to place x 
> relative to y. So if it yields .orderedAscending, then x comes before y. This 
> will be considered the new “main” dispatch point of Comparable that 
> implementors should provide.
> 
> Most code will continue to use < or ==, as it will be optimal for their 
> purposes. However code that needs to make a three-way branch on comparison 
> can use the potentially more efficient compare. Note that compare is only 
> expected to be more efficient in this specific case. If a two-way branch is 
> all that’s being done, < will be more efficient in many cases (if only 
> because it’s easier for the optimizer).
> 
> For backwards compatibility reasons, compare will have a default 
> implementation defined in terms of <, but to enable only using compare, < and 
> == will also have default implementations in terms of compare.
> 
> The compiler will verify that either compare, or < and ==, are provided by 
> every type that claims to conform to Comparable. This will be done in some 
> unspecified way unavailable outside the standard library (it can be made 
> available to in the future, but that’s an unnecessary distraction for this 
> proposal).
> 
> Types that wish to provide comparison “variants” can do so naturally by 
> adding compare methods with additional arguments. e.g. String.compare(_ 
> other: Self, in: Locale) -> ComparisonResult. These have no 

[swift-evolution] [pitch] Comparison Reform

2017-04-13 Thread Ben Cohen via swift-evolution

Hi swift evolution,

Here’s another pitch, for The Propoosal Formerly Known As Spaceship.
Comparison Reform

Proposal: SE- 

Authors: Robert Widmann , Jaden Geller 
, Harlan Haskins 
, Alexis Beingessner 
, Ben Cohen 
Status: Awaiting review
Review manager: TBD
Introduction

This proposal is for changes that we believe should be made to the existing 
comparison system by:

Making FloatingPoint comparison context sensitive, so that its Comparable 
conformance provides a proper total ordering.
Introducing a new ternary-valued compare(_ other: Self) -> ComparisonResult 
method.
Removing unnecessary customization points from Comparable.
Motivation

The motivation comes from several independent points:

1: The standard comparison operators have an intuitive meaning to programmers. 
Swift encourages encoding that in an implementation of Comparable that respects 
the rules of a total order . The 
standard library takes advantage of these rules to provide consistent 
implementations for sorting and searching generic collections of Comparable 
types.

Not all types behave so well in this framework, unfortunately. There are cases 
where the semantics of a total order cannot apply while still maintaining the 
traditional definition of “comparison” for these types. Take, for example, 
sorting an array of Floats. Today, Float’s instance of Comparable follows 
IEEE-754 and returns false for all comparisons of NaN. In order to sort this 
array, NaN s are considered outside the domain of <, and the order of a sorted 
array containing them is unspecified. Similarly, a Dictionary keyed off floats 
can leak entries and memory.

2: Generic algorithms in the Swift Standard Library that make use of the 
current Comparable protocol may have to make extra comparisons to determine the 
ordering of values when <, ==, and > should have different behaviours. Having a 
central operation to return complete ordering information should provide a 
speedup for these operations.

3: The existing comparison operators don’t “generalize” well. There’s no clean 
way to add a third or fourth argument to < to ask for non-default semantics. An 
example where this would be desirable would be specifying the locale or 
case-sensitivity when comparing Strings.

4: Comparable is over-engineered in the customization points it provides: to 
our knowledge, there’s no good reason to ever override >=, >, or <=. Each 
customization point bloats vtables and mandates additional dynamic dispatch.

5: When quickly writing a Comparable type, it is easier to implement a single 
ternary statement than to separately implement == and <.

Proposed solution

ComparisonResult

Foundation’s ComparisonResult type will be mapped into Swift as

@objc public enum ComparisonResult : Int {
  case orderedAscending = -1
  case orderedSame = 0
  case orderedDescending = 1
}
Comparable

Comparable will be changed to have a new ternary comparison method: compare(_ 
other: Self) -> ComparisonResult. x.compare(y) specifies where to place x 
relative to y. So if it yields .orderedAscending, then x comes before y. This 
will be considered the new “main” dispatch point of Comparable that 
implementors should provide.

Most code will continue to use < or ==, as it will be optimal for their 
purposes. However code that needs to make a three-way branch on comparison can 
use the potentially more efficient compare. Note that compare is only expected 
to be more efficient in this specific case. If a two-way branch is all that’s 
being done, < will be more efficient in many cases (if only because it’s easier 
for the optimizer).

For backwards compatibility reasons, compare will have a default implementation 
defined in terms of <, but to enable only using compare, < and == will also 
have default implementations in terms of compare.

The compiler will verify that either compare, or < and ==, are provided by 
every type that claims to conform to Comparable. This will be done in some 
unspecified way unavailable outside the standard library (it can be made 
available to in the future, but that’s an unnecessary distraction for this 
proposal).

Types that wish to provide comparison “variants” can do so naturally by adding 
compare methods with additional arguments. e.g. String.compare(_ other: Self, 
in: Locale) -> ComparisonResult. These have no language-level connection to 
Comparable, but are still syntactically connected, implying the same total 
order semantics. This makes them easier to discover, learn, and migrate to.

To reduce bloat, the operators <=, >=, and > will be removed from the set of 
requirements that the Comparable protocol declares. These operators will 
however continue to exist with the current default implementations.

FloatingPoint

No changes will be made to the 

Re: [swift-evolution] [Pitch] Cross-platform Swift TLS library

2017-04-13 Thread Bouke Haarsma via swift-evolution

Hi Gelareh,

Overall I think this pitch is a great move forward. 

I've found that this is already resulting in some incompatibilities 
trying to combine rather complex Swift projects. I recently worked on 
integrating Kitura-Net, which uses BlueCryptor as a wrapper over both 
CommonCrypto / OpenSSL. I was delighted by BlueCryptor, as it proved to 
be a somewhat drop-in replacement for my custom CommonCrypto overlay. 
Seeing that this pitch moves along the same lines, I'm all for.


Some inline comments below.

-Bouke

On 2017-04-06 16:16:51 +, Gelareh Taban via swift-evolution said:


# Problem
Since there is currently no standard Swift SSL/TLS library that is 
compatible on both Apple and Linux, Swift projects use their TLS 
library of choice (such as OpenSSL, LibreSSL, Security framework, etc). 
This results in:
- fragmentation of the space as well as incompatibility of project 
dependencies if more than one security package is needed by different 
modules (a project cannot have both OpenSSL and LibreSSL in its 
dependency graph)
- insecurity (using an unpatched or deprecated library such as OpenSSL 
on macOS)


This is even more true for Homebrew which refuses to link OpenSSL as 
those links might confuse the OS to link to the system's library 
instead (which is even more outdated). There's quite a bit incorrect 
"advice" floating around on how to create those symlinks.



- unmaintainablity (using non-standard or non-native libraries)
- more complex code (using different APIs or code paths for each platform).

So we want to propose a standard set of protocols that define the 
behavior of the TLS service and how the application and the server and 
networking layers beneath it interact with the TLS service. What 
complicates this pitch is that the Swift in server space is new and 
none of the interfaces have yet been defined, so this is really a work 
in iteration.


# Design goals

We came up with the following design goals for a solution:

- Provide a consistent and unified Swift interface so that the 
developer can write simple, cross-platform applications;
- Don't implement new crypto functionality and instead use existing 
functions in underlying libraries;
- Plug-n-play architecture which allows the developer to decide on 
underlying security library of choice, e.g., OpenSSL vs LibreSSL;
- Library should be agnostic of the transport mechanism (e.g., socket, 
etc), whilst allowing for both blocking and non-blocking connections;
- Developers should be able to use the same TLS library for both client 
and server applications.


+1

Additionally I'd like to see and API that:

- is designed for "ease of use"
- is strong typed
- integrates well with Foundation (DispatchQueue)
- fosters good performance (threading)


# Proposal
(...)


I'm not deeply familiar with the topic, so no comments on this part.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0166: Swift Archival & Serialization

2017-04-13 Thread Karl Wagner via swift-evolution
> What goes into a review?
> The goal of the review process is to improve the proposal under review 
> through constructive criticism and, eventually, determine the direction of 
> Swift. When writing your review, here are some questions you might want to 
> answer in your review:
> 
> What is your evaluation of the proposal?
-1

The proposal is mis-named; it isn’t Swift Archival and Serialisation. What it 
really is, is Foundation Archival and Serialisation. The proposal doesn’t even 
mention where these new protocols and types will live, but the general talk is 
all about Foundation and nothing at all about the standard library, so I’m 
assuming that’s where they will go.

- I fundamentally disagree with having the conformance be synthesised. We don’t 
do this anywhere else in the language, AFAIK. I believe it will make it easier 
for naive developers to suffer privacy leaks, or cause hard-to-debug crashes 
because they were persisting and restoring non-persistable values.

- I believe the proposal is premature. It is likely that Smart KeyPaths would 
allow us to define a collection of serialisable details of an instance in a 
convenient way which does not require compiler magic. Such a design could also 
allow more features than the one proposed (KeyPaths can select particular 
details from deep within properties, and the “collection" could be a Dictionary 
of KeyPaths to Serialisation Keys). A lot of effort has been made to make this 
all “magic” and automatic, but I see that as an anti-goal. I believe we are 
close to being able to write a safe, convenient serialisation API without the 
need for hidden and un-debuggable synthesis. This proposal should wait.

- Not only that, but I feel it would muddy the line between the Swift language 
and Foundation beyond what is acceptable. Those libraries are crucial to 
Apple’s platforms, so it’s understandable that you’re so protective of them, 
but I personally feel they are very far from what the “core libraries” of Swift 
could be. For example, having separate Data and DispatchData types, and no 
owned reference-counted buffer in the standard library at all is a horrible 
design IMO. Even minor pull-requests in to the core libraries seems to require 
herculean amounts of effort 
(https://github.com/apple/swift-corelibs-libdispatch/pull/172 
https://github.com/apple/swift/pull/7446), so I have precisely 0 hope of 
anybody outside of Apple bringing any fresh ideas or improvements to the table.

I don’t want to go too much in to my gripes with Foundation and Dispatch, but 
suffice to say that giving them special language consideration is a step too 
far. This is Apple proposing a design that’s good for Apple and nobody else, 
and I’m not in favour of breaking layering even further to accomplish it.

> Is the problem being addressed significant enough to warrant a change to 
> Swift?
No. I feel the solution is disproportionate to the problem.

> Does this proposal fit well with the feel and direction of Swift?
It’s a poor design, only differing from existing libraries in how 
Apple-specific it is, and the principle-breaking language magic needed in order 
to achieve it. It does not fit at all with much better proposals, like Smart 
KeyPaths. Maybe the authors should have co-ordinated more with others before 
proposing it. And presenting an implementation PR at the same time just feels 
wrong IMO, like Apple expects to have this proposal rubber-stamped for their 
SDK plans.

> If you have used other languages or libraries with a similar feature, how do 
> you feel that this proposal compares to those?
I also develop for Android, and it’s extremely easy to implement serialisation 
using annotation-based libraries such as Icepick 
(https://github.com/frankiesardo/icepick).
I even feel like that is too much magic sometimes, but I’d prefer an 
annotation-based solution to invisible conformance synthesis any day of the 
week.

> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?
I read the previous discussions, and have read and re-read the proposal a 
couple of times.


> More information about the Swift evolution process is available at
> 
> https://github.com/apple/swift-evolution/blob/master/process.md 
> 
> Thank you,
> 
> -Doug
> 
> Review Manager
> 
> ___
> 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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Sure thing, everyones opinion is welcome and helps fine tuning the model.

Here is a quick illustration of the model I’m pushing.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 20:02:44, David Sweeris (daveswee...@mac.com) schrieb:


On Apr 13, 2017, at 10:52, Adrian Zubarev  
wrote:

I don’t think it’s a good idea to add optionally character before the closing 
delimiter, because it could confuse the reader of the code on how exactly the 
actual string lines above will be stripped.

My personal vision remains as the following example:

// 1)
"""
Line_1
Line_2
"""

// result for 1)
"Line_1\nLine_2"

// 2)
"""

Line_1
Line_2
"""

// result for 2)
"\nLine_1\nLine_2"

// 3)
"""
Line_1
Line_2

"""

// result for 3)
"Line_1\nLine_2\n"

// 4)
"""

Line_1
Line_2

"""

// result for 4)
"\nLine_1\nLine_2\n"
This is the natural approach, alternatively you’re free to use directly \n 
instead a blank line.


I think I'm inclined to agree... I'm just trying to think of ways to make those 
who don't agree happy as well. Of course, as you pointed out, that necessarily 
complicates things, which is itself something to consider.

Fortunately, we can add the syntax (or something else equally simple) to flip 
the leading/trailing newline stripping behavior later, if it becomes necessary.

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


Re: [swift-evolution] [pitch] One-sided Ranges

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 12, 2017, at 20:31, Félix Cloutier via swift-evolution 
>  wrote:
> 
> I don't have a strong opinion; are we sure enough that this is what we want 
> the postfix operator … to be for? For instance, C++ uses it a lot with 
> variadic templates.

I don't think the two usages conflict... maybe later if "literal values as 
generic parameters" and "variadic generic parameters" get added, there might be 
a problem involving variadic literal one-sided ranges, but otherwise we should 
be good on that front... I think...

I should probably learn more about how C++ templates have changed since they 
were first introduced.

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 13, 2017, at 10:52, Adrian Zubarev  
> wrote:
> 
> I don’t think it’s a good idea to add optionally character before the closing 
> delimiter, because it could confuse the reader of the code on how exactly the 
> actual string lines above will be stripped.
> 
> My personal vision remains as the following example:
> 
> // 1)
> """
> Line_1
> Line_2
> """
> 
> // result for 1)
> "Line_1\nLine_2"
> 
> // 2)
> """
> 
> Line_1
> Line_2
> """
> 
> // result for 2)
> "\nLine_1\nLine_2"
> 
> // 3)
> """
> Line_1
> Line_2
> 
> """
> 
> // result for 3)
> "Line_1\nLine_2\n"
> 
> // 4)
> """
> 
> Line_1
> Line_2
> 
> """
> 
> // result for 4)
> "\nLine_1\nLine_2\n"
> This is the natural approach, alternatively you’re free to use directly \n 
> instead a blank line.
> 
> 

I think I'm inclined to agree... I'm just trying to think of ways to make those 
who don't agree happy as well. Of course, as you pointed out, that necessarily 
complicates things, which is itself something to consider.

Fortunately, we can add the syntax (or something else equally simple) to flip 
the leading/trailing newline stripping behavior later, if it becomes necessary.

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
I don’t think it’s a good idea to add optionally character before the closing 
delimiter, because it could confuse the reader of the code on how exactly the 
actual string lines above will be stripped.

My personal vision remains as the following example:

// 1)
"""
Line_1
Line_2
"""

// result for 1)
"Line_1\nLine_2"

// 2)
"""

Line_1
Line_2
"""

// result for 2)
"\nLine_1\nLine_2"

// 3)
"""
Line_1
Line_2

"""

// result for 3)
"Line_1\nLine_2\n"

// 4)
"""

Line_1
Line_2

"""

// result for 4)
"\nLine_1\nLine_2\n"
This is the natural approach, alternatively you’re free to use directly \n 
instead a blank line.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 19:47:18, David Sweeris (daveswee...@mac.com) schrieb:


On Apr 13, 2017, at 10:41, Adrian Zubarev  
wrote:

Was the / intended or did you meant to write \?

Personally I don’t think we’d need that behavior and can fallback to the 
natural way using a blank lines or explicit way using the \n character to solve 
that issue at the top or bottom of the multi-line string. The model I’m pushing 
already would support “paste-in block of text as-is”. :)

Hah, oops, yeah. Although maybe the "/" would be better for the closing """, 
since that one affects whether the preceding "\n" character is escaped.

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Vladimir.S via swift-evolution

On 13.04.2017 15:41, Brent Royal-Gordon via swift-evolution wrote:
On Apr 13, 2017, at 5:35 AM, Ricardo Parada via swift-evolution 
> wrote:


Take a look at Brent's revised proposal.I personally thin it is perfect.  Take 
a look:

https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md


Well, um, looks like we got scooped. (I was playing with some non-essential wording 
and trying to test all the examples before I pointed the list at the new version.)


FWIW Although I still believe that allowing text on the same line with opening or 
closing """ (except for the single-line case) is over-complicating of the model and 
adding unnecessary point of confusion, especially for the reader of code("will new 
line be inserted here?!well.. for this special case I have to check docs"..), I can 
give +1 for this updated proposal as it provides correct(from my point of view) 
behavior for "normal" multi-line string like


"""
line 1
line 2
"""

-> "line 1\nline 2\n"



Since requiring a leading backslash went over like a lead balloon, we've revised the 
proposal one more time. The leading newline is now optional: If indentation stripping 
is enabled, you can either start typing content on the same line as the delimiter, or 
you can start on the next line. I resisted this solution for a while because it seems 
ad-hoc, but ultimately it's the design that preserves the most formatting flexibility 
for the user, so I think it's the right way to go.


Other than that, there are no changes to the design in this revision, though I've 
rephrased a few things and added a section about why we strip a leading newline but 
not a trailing one.


John has also built a new version of the toolchain which matches this behavior. 
Download it here: http://johnholdsworth.com/swift-LOCAL-2017-04-13-a-osx.tar.gz


Thanks for your feedback!

--
Brent Royal-Gordon
Architechies



___
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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 13, 2017, at 10:41, Adrian Zubarev  
> wrote:
> 
> Was the / intended or did you meant to write \?
> 
> Personally I don’t think we’d need that behavior and can fallback to the 
> natural way using a blank lines or explicit way using the \n character to 
> solve that issue at the top or bottom of the multi-line string. The model I’m 
> pushing already would support “paste-in block of text as-is”. :)
> 
Hah, oops, yeah. Although maybe the "/" would be better for the closing """, 
since that one affects whether the preceding "\n" character is escaped.

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Was the / intended or did you meant to write \?

Personally I don’t think we’d need that behavior and can fallback to the 
natural way using a blank lines or explicit way using the \n character to solve 
that issue at the top or bottom of the multi-line string. The model I’m pushing 
already would support “paste-in block of text as-is”. :)

Glad to have you joining the discussion.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 19:33:42, David Sweeris via swift-evolution 
(swift-evolution@swift.org) schrieb:


On Apr 12, 2017, at 07:52, Thorsten Seitz via swift-evolution 
 wrote:

Am 12.04.2017 um 15:40 schrieb Brent Royal-Gordon via swift-evolution 
:

Hey folks,


We've revised the proposal again. The main difference: You no longer need an 
initial newline to enable indentation stripping, and stripping no longer 
removes that newline even if it is present. (Adrian Zubarev and I believe some 
others argued for this.) We

Hmm, not sure if I like these changes. I expect that almost all strings won't 
begin with a newline and a majority won’t end with a newline. The new design 
would require a leading backslash almost all the time and a trailing backslash 
often, which is ugly:

let mystring = "““\
   text text
   text text\
   "““

(I think I've read the whole thread, but it can be easy to miss parts on the 
phone. I think this is different than what's already been discussed... sorry if 
this has already been suggested and I just missed it.)

What having this input:
let mystring = "““
   text text
   text text
   "““
yielding this output:
text text
text text

And this input:
let mystring = "““/
   text text
   text text
   /"““
yielding this output:

text text
text text


(Sorry about not putting in all the symbols... I don't know a way to type them 
on my phone)

If you think of the "/" as more of a "toggle whether the next character is 
escaped" instead of specifically "escape the next character", it makes sense 
(kinda)... or the outputs could be reversed. Either way, it allows easy access 
to both options and preserves the "paste-in block of text as-is" goal.

- 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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread David Sweeris via swift-evolution

On Apr 12, 2017, at 07:52, Thorsten Seitz via swift-evolution 
 wrote:

>> Am 12.04.2017 um 15:40 schrieb Brent Royal-Gordon via swift-evolution 
>> :
>> 
>> Hey folks,
>> 
>> 
>> We've revised the proposal again. The main difference: You no longer need an 
>> initial newline to enable indentation stripping, and stripping no longer 
>> removes that newline even if it is present. (Adrian Zubarev and I believe 
>> some others argued for this.) We
> 
> Hmm, not sure if I like these changes. I expect that almost all strings won't 
> begin with a newline and a majority won’t end with a newline. The new design 
> would require a leading backslash almost all the time and a trailing 
> backslash often, which is ugly:
> 
> let mystring = "““\
>text text
>text text\
>"““

(I think I've read the whole thread, but it can be easy to miss parts on the 
phone. I think this is different than what's already been discussed... sorry if 
this has already been suggested and I just missed it.)

What having this input:
> let mystring = "““
>text text
>text text
>"““

yielding this output:
> text text
> text text

And this input:
> let mystring = "““/
>text text
>text text
>/"““

yielding this output:
> 
> text text
> text text
> 

(Sorry about not putting in all the symbols... I don't know a way to type them 
on my phone)

If you think of the "/" as more of a "toggle whether the next character is 
escaped" instead of specifically "escape the next character", it makes sense 
(kinda)... or the outputs could be reversed. Either way, it allows easy access 
to both options and preserves the "paste-in block of text as-is" goal.

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


Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Jeff Kelley via swift-evolution
Yes, the idea was to key off of an optional index. something like this:

> extension Array {
> public subscript(_ index: Int?) -> Element? {
> guard let i = index, i < endIndex else { return nil }
> 
> return self[i]
> }
> }
> 
> let array = ["foo", "bar", "baz"]
> 
> array[1] // "bar"
> 
> let index: Int? = 5
> let notInArray = array[index]

This doesn’t work today with the error “ambiguous use of 'subscript’” on 
“self[i]” but surely that could be fixed.


Jeff Kelley

slauncha...@gmail.com | @SlaunchaMan  | 
jeffkelley.org 
> On Apr 13, 2017, at 12:18 PM, David Sweeris  wrote:
> 
> 
>> On Apr 13, 2017, at 08:53, Josh Parmenter  wrote:
>> 
>> This seems inconsistent to me. 2 is 2... 2 itself is not optional. You 
>> wouldn't expect 2 to be unwrapped.
> 
> Correct. I think the idea was that "2?" would get converted to an 
> `Optional`, which would then call a subscript that took an `Index?` 
> instead of `Index`. The trailing "?" doesn't do that, but for some reason I 
> thought it might.
> 
> IMHO, the semantics are clear(ish) in context, but it feels slightly odd for 
> "?" to have two opposite behaviors depending on whether the argument is or 
> isn't an Optional.
> 
> In any case, given that we're discussing a "safe subscript", we need a way to 
> differentiate the safe subscript from the unsafe subscript. The only two ways 
> to do that are to either add an argument label or change the argument type, 
> and IMHO the best alternate argument type is `Index?`, since it's pretty 
> light-weight, already part of the stdlib, and already familiar to Swift 
> developers.
> 
> Someone already said it was a bad idea, though, so I'm rethinking my support.
> 
> - Dave Sweeris 
> 

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Btw. shouldn’t we let the core return the current proposal officially for 
revision, or otherwise it will need to stay ‘long enough’ in it’s revisioned 
pitch state before we can kick off a second review process!

Just saying.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 18:21:29, Adrian Zubarev (adrian.zuba...@devandartist.com) 
schrieb:

I’ve update my gist to reflect that now: 
https://gist.github.com/DevAndArtist/dae76d4e3d4e49b1fab22ef7e86a87a9

Simple ‘multi-line string literal’ model

Core features:

Omitting of (most) backslashes for ".
Altering the string with implicit new line injection at the end of the line.
Sting interpolation (trivial in terms of consistency and functionality).
Consequences of #1:

To omit escaping the quote character, the delimiter characters for the 
multi-line string literal will be tripled quotes """, also similar to other 
programming languages.

When a standard string literal contains at least 5 quotes, then the usage of a 
multi-line string literal can be shorter.

""// With escapes
""  // With tripled literals
Consequences of #2:

To fully support this feature, we need to compromise the design for simplicity 
and intuitivity.

This feature needs precision for leading and trailing whitespaces.

Alternatively one would need a way to disable new line injection to also 
support code formatting.

Two ways of writing a multi-line string literal:

Single line version """abc""" is trivial and already was shown above.

The multi-line version comes with a few compromises for simplicity of rules:

"""   // DS (delimiter start)
foo   // s0
foo   // s1
foo   // s2
"""   // DE (delimiter end)
The string content is always written between the lines DS and DE (delimiter 
lines).
That means that the following snippets are not allowed:

// Banned option 1:
"""foo
   foo
   """   
 
// Banned option 2:   
"""foo
   foo"""   
 
// Banned option 3:
"""
foo
foo"""   
To not to go the continuation quotes path, the left (or leading) precision is 
handled by the closing delimiter (1. compromise). The closing delimiter is also 
responsible for the indent algorithm, which will calculate the stripping prefix 
in line DE and apply stripping to lines s0 to sn.

Right (or trailing) precision of each line from s0 to sn (notice n equals 2 in 
the example above) is handled by a backslash character (2. compromise).

The right precision comes at a price of losing the implicit new line injection, 
however this was also a requested feature (3. compromise). That means that the 
backslash can serve two jobs simultaneously.

New line injection happens only on lines s0 to s(n - 1) (4. and last compromise 
of the design). The last line sn (or s2 above) does not inject a new line into 
the final string. This implies that in this line a backslash character handles 
only right precision, or one could say it’s reduced for one functionality.

The following multi-line string literal

print("""
  foo
  foo
  """)
will produce the string “foo\nfoo” and only print:

foo
foo
Important:

Because whitespace is important to these examples, it is explicitly indicated: 
· is a space, ⇥ is a tab, and ↵ is a newline.

Leading/trailing precision and indent (1. and 2. compromise):

// Nothing to strip in this example (no indent).
let str_1 = """↵   
foo↵
"""

// No right precision (no backslash), but presence of whitespace   
// characters will emit a warning.
let str_2 = """↵   
foo··↵
"""
Warning:

warning: line # includes trailing whitespace characters in multi-line string 
literal without the precision `\` character at the end
  foo··↵
 ~~
  Fix-it: Insert "\n\" after the last space character (or only `\` if it's the 
`sn` line)
More examples:

// Simmilar to `str_2`
let str_3 = """↵   
foo↵
"""

// Line `DE` of the closing delimiter calculates the indent prefix   
// `··` and strips it from `s0` (left precision).
let str_4 = """↵   
··foo↵
··"""

// Line `DE` of the closing delimiter calculates the indent prefix   
// `` and strips it from `s0` (left precision).
//
// No right precision (no backslash), but presence of whitespace   
// characters will emit a warning.
let str_5 = """↵   
foo··↵
"""

// Line `DE` of the closing delimiter calculates the indent prefix   
// `⇥ ⇥ ` and strips it from `s0` (left precision).
//
// Right precision is applied (backslash). In this case the literal
// contains only a single line of content, which happens to be
// also the last line before `DE` -> backslash only serves precision.
let str_6 = """↵   
⇥ ⇥ foo\↵
⇥ ⇥ """

// Line `DE` of the closing delimiter calculates the indent prefix   
// `·⇥ ·⇥ ` and strips it from `s0` (left precision).
//
// No right precision (no backslash), but presence of whitespace   
// characters will emit a warning.
let str_7 = """↵   
·⇥ ·⇥ foo··↵
·⇥ ·⇥ """

let string_1 = "foo"

str_1 == string_1   // => true
str_2 == string_1   // => false
str_3 == string_1   // => false
str_4 == string_1   // => 

Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
I’ve update my gist to reflect that now: 
https://gist.github.com/DevAndArtist/dae76d4e3d4e49b1fab22ef7e86a87a9

Simple ‘multi-line string literal’ model

Core features:

Omitting of (most) backslashes for ".
Altering the string with implicit new line injection at the end of the line.
Sting interpolation (trivial in terms of consistency and functionality).
Consequences of #1:

To omit escaping the quote character, the delimiter characters for the 
multi-line string literal will be tripled quotes """, also similar to other 
programming languages.

When a standard string literal contains at least 5 quotes, then the usage of a 
multi-line string literal can be shorter.

""// With escapes
""  // With tripled literals
Consequences of #2:

To fully support this feature, we need to compromise the design for simplicity 
and intuitivity.

This feature needs precision for leading and trailing whitespaces.

Alternatively one would need a way to disable new line injection to also 
support code formatting.

Two ways of writing a multi-line string literal:

Single line version """abc""" is trivial and already was shown above.

The multi-line version comes with a few compromises for simplicity of rules:

"""   // DS (delimiter start)
foo   // s0
foo   // s1
foo   // s2
"""   // DE (delimiter end)
The string content is always written between the lines DS and DE (delimiter 
lines).
That means that the following snippets are not allowed:

// Banned option 1:
"""foo
   foo
   """  

// Banned option 2:  
"""foo
   foo"""  

// Banned option 3:
"""
foo
foo"""  
To not to go the continuation quotes path, the left (or leading) precision is 
handled by the closing delimiter (1. compromise). The closing delimiter is also 
responsible for the indent algorithm, which will calculate the stripping prefix 
in line DE and apply stripping to lines s0 to sn.

Right (or trailing) precision of each line from s0 to sn (notice n equals 2 in 
the example above) is handled by a backslash character (2. compromise).

The right precision comes at a price of losing the implicit new line injection, 
however this was also a requested feature (3. compromise). That means that the 
backslash can serve two jobs simultaneously.

New line injection happens only on lines s0 to s(n - 1) (4. and last compromise 
of the design). The last line sn (or s2 above) does not inject a new line into 
the final string. This implies that in this line a backslash character handles 
only right precision, or one could say it’s reduced for one functionality.

The following multi-line string literal

print("""
  foo
  foo
  """)
will produce the string “foo\nfoo” and only print:

foo
foo
Important:

Because whitespace is important to these examples, it is explicitly indicated: 
· is a space, ⇥ is a tab, and ↵ is a newline.

Leading/trailing precision and indent (1. and 2. compromise):

// Nothing to strip in this example (no indent).
let str_1 = """↵  
foo↵
"""

// No right precision (no backslash), but presence of whitespace  
// characters will emit a warning.
let str_2 = """↵  
foo··↵
"""
Warning:

warning: line # includes trailing whitespace characters in multi-line string 
literal without the precision `\` character at the end
  foo··↵
 ~~
  Fix-it: Insert "\n\" after the last space character (or only `\` if it's the 
`sn` line)
More examples:

// Simmilar to `str_2`
let str_3 = """↵  
foo↵
"""

// Line `DE` of the closing delimiter calculates the indent prefix  
// `··` and strips it from `s0` (left precision).
let str_4 = """↵  
··foo↵
··"""

// Line `DE` of the closing delimiter calculates the indent prefix  
// `` and strips it from `s0` (left precision).
//
// No right precision (no backslash), but presence of whitespace  
// characters will emit a warning.
let str_5 = """↵  
foo··↵
"""

// Line `DE` of the closing delimiter calculates the indent prefix  
// `⇥ ⇥ ` and strips it from `s0` (left precision).
//
// Right precision is applied (backslash). In this case the literal
// contains only a single line of content, which happens to be   
// also the last line before `DE` -> backslash only serves precision.
let str_6 = """↵  
⇥ ⇥ foo\↵
⇥ ⇥ """

// Line `DE` of the closing delimiter calculates the indent prefix  
// `·⇥ ·⇥ ` and strips it from `s0` (left precision).
//
// No right precision (no backslash), but presence of whitespace  
// characters will emit a warning.
let str_7 = """↵  
·⇥ ·⇥ foo··↵
·⇥ ·⇥ """

let string_1 = "foo"

str_1 == string_1   // => true
str_2 == string_1   // => false
str_3 == string_1   // => false
str_4 == string_1   // => true
str_5 == string_1   // => false
str_6 == string_1   // => true
str_7 == string_1   // => false
A wrong multi-line string literal, which compiles but emits a warning with a 
fix-it:

let str_8 = """↵  
··foo↵
"""

str_8 == string_1   // => true
Warning:

warning: missing indentation in multi-line string literal
  ··foo
^  
  Fix-it: Insert "··"
The stripping 

Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 13, 2017, at 08:53, Josh Parmenter  wrote:
> 
> This seems inconsistent to me. 2 is 2... 2 itself is not optional. You 
> wouldn't expect 2 to be unwrapped.

Correct. I think the idea was that "2?" would get converted to an 
`Optional`, which would then call a subscript that took an `Index?` 
instead of `Index`. The trailing "?" doesn't do that, but for some reason I 
thought it might.

IMHO, the semantics are clear(ish) in context, but it feels slightly odd for 
"?" to have two opposite behaviors depending on whether the argument is or 
isn't an Optional.

In any case, given that we're discussing a "safe subscript", we need a way to 
differentiate the safe subscript from the unsafe subscript. The only two ways 
to do that are to either add an argument label or change the argument type, and 
IMHO the best alternate argument type is `Index?`, since it's pretty 
light-weight, already part of the stdlib, and already familiar to Swift 
developers.

Someone already said it was a bad idea, though, so I'm rethinking my support.

- Dave Sweeris 

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


Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Josh Parmenter via swift-evolution
This seems inconsistent to me. 2 is 2... 2 itself is not optional. You wouldn't 
expect 2 to be unwrapped.
Best
Josh

Sent from my iPhone

On Apr 13, 2017, at 08:48, Jeff Kelley via swift-evolution 
> wrote:

Apologies if this has been suggested before, but going off of Andrew's message, 
a simple syntax could be to use our existing Optional syntax:

let array = ["foo", "bar", "baz"]

let first = array[0] // type is `String`
let third = array[2?] // type is `String?`, value is .some("baz")
let fourth = array[3?] // type is `String?`, value is .none

Jeff Kelley

slauncha...@gmail.com | 
@SlaunchaMan | 
jeffkelley.org

On Apr 13, 2017, at 8:19 AM, David Sweeris via swift-evolution 
> wrote:


On Apr 13, 2017, at 3:56 AM, Andrew Hart via swift-evolution 
> wrote:

Recently I've been considering the lack of safety around array indexes. Swift 
is designed with safety in mind, so this example would not compile:

var myString: String? = "hello"
myString.append(" world!")

The string is optional, not guaranteed to exist, so the last line requires a 
"!" to force-unwrap it.



public func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
let section = self.sections[section]

return section.items.count
}

In this example, we could provide a section number that goes beyond the bounds 
of the self.sections array, without any warning.

My suggestion is perhaps arrays should by default return an optional when given 
an index, and of course they'd support forced-unwrapping too. So you could then 
do this:

let section = self.sections[section]
if section == nil {
return 0
} else {
return section!.items.count
}

Or you could do this:

let section = self.sections[section]!

return section.items.count

Of course this would be less convenient in a lot of cases, but this is the 1 
place where apps seem to encounter a crash, crashing for the same reason that's 
especially avoided across most of the rest of Swift.

My understanding is that we need the current behavior to meet performance 
goals. We've discussed adding a "safe" subscript before, but the discussion 
usually fizzles out when no clear winner for the argument label emerges.

- 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
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Lucas Neiva via swift-evolution
I think most people would agree with “its a Not a Great Idea (™)”.

The root argument is “out-of-bounds array access is a logic error”.

> On 13.04.2017, at 16:54, David Sweeris via swift-evolution 
>  wrote:
> 
> 
> 
> 
> Sent from my iPhone
> On Apr 13, 2017, at 07:34, Jeff Kelley  wrote:
> 
>> Apologies if this has been suggested before, but going off of Andrew’s 
>> message, a simple syntax could be to use our existing Optional syntax:
>> 
>> let array = ["foo", "bar", "baz"]
>> 
>> let first = array[0] // type is `String`
>> let third = array[2?] // type is `String?`, value is .some("baz")
>> let fourth = array[3?] // type is `String?`, value is .none
> 
> That was my thought, too, but it's not valid Swift. I tried it in a 
> playground before I sent my reply. At least in Xcode 8.3.1, it gives an error 
> about ambiguous calls (it can't decide if you're trying to call the stdlib 
> subscript or the `(_: Index?) -> Element?` one from the extension), and if 
> you fix that by adding an argument label, the real issue is revealed which is 
> that saying "x?" doesn't return "x wrapped in an optional"; it thinks you're 
> trying to do Optional chaining on a non-optional value, which isn't allowed.
> 
> I wouldn't object to adding that "trailing '?' wraps the value" behavior (or 
> maybe "¿", since they really would have the opposite result), in which case 
> this should work fine (although the choice of argument label, or lack 
> thereof, will likely still be bikeshedded)
> 
> Anyway, unless someone who knows more about this than I do (probably most of 
> you) says this functionality is a Bad Idea (™), I'm in favor of it.
> 
> - 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] [Pitch] Adding safety to arrays

2017-04-13 Thread David Sweeris via swift-evolution



Sent from my iPhone
> On Apr 13, 2017, at 07:34, Jeff Kelley  wrote:
> 
> Apologies if this has been suggested before, but going off of Andrew’s 
> message, a simple syntax could be to use our existing Optional syntax:
> 
> let array = ["foo", "bar", "baz"]
> 
> let first = array[0] // type is `String`
> let third = array[2?] // type is `String?`, value is .some("baz")
> let fourth = array[3?] // type is `String?`, value is .none

That was my thought, too, but it's not valid Swift. I tried it in a playground 
before I sent my reply. At least in Xcode 8.3.1, it gives an error about 
ambiguous calls (it can't decide if you're trying to call the stdlib subscript 
or the `(_: Index?) -> Element?` one from the extension), and if you fix that 
by adding an argument label, the real issue is revealed which is that saying 
"x?" doesn't return "x wrapped in an optional"; it thinks you're trying to do 
Optional chaining on a non-optional value, which isn't allowed.

I wouldn't object to adding that "trailing '?' wraps the value" behavior (or 
maybe "¿", since they really would have the opposite result), in which case 
this should work fine (although the choice of argument label, or lack thereof, 
will likely still be bikeshedded)

Anyway, unless someone who knows more about this than I do (probably most of 
you) says this functionality is a Bad Idea (™), I'm in favor of it.

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


Re: [swift-evolution] [Review] SE-0166: Swift Archival & Serialization

2017-04-13 Thread Jon Shier via swift-evolution
> And all of this is only an issue if you write the conformance by hand in the 
> first place. Usually, you won't.

Brent, given that this API is designed not just for NSKeyedArchiver-like usage, 
but to form the basis of serialization to and from JSON, among other network 
types, I really don’t think this is true. It just won’t work by default for 
JSON, if only because JSON has informally standardized on snake-case keys 
(some_key). AFAICT, this proposal has nothing to enable developers to define a 
key convention that automatically generates such keys. So, from my perspective, 
every single use of the proposed APIs that isn’t just a replacement for 
NSKeyedArchiver will be forced to manually implement the entire API, unless 
developers get lucky and somehow get a representation that fits a good Swift 
type exactly. That just doesn’t happen. There are so many bad JSON APIs out 
there that being able to easily define different keys and transforms of a JSON 
type to some Swift type isn’t just a convenience, it’s a requirement.




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


Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Lucas Neiva via swift-evolution
AFAIK arrays use the same “subscripts” [1] feature as other collections. So 
this feature would have to be tagged onto subscripts in general.

I see a few problems with you suggestion:

- How do you differentiate between an out-of-bounds subscript access in an 
array with optional elements, e.g. `[String?]`, `[Int: String?]`
- Isn’t it conflating two different things, to use the same `?` operator here
- You’d probably have to add a new construct similar to the existing subscripts 
feature


[1] 
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html


> On 13.04.2017, at 16:34, Jeff Kelley via swift-evolution 
>  wrote:
> 
> Apologies if this has been suggested before, but going off of Andrew’s 
> message, a simple syntax could be to use our existing Optional syntax:
> 
> let array = ["foo", "bar", "baz"]
> 
> let first = array[0] // type is `String`
> let third = array[2?] // type is `String?`, value is .some("baz")
> let fourth = array[3?] // type is `String?`, value is .none
> 
> Jeff Kelley
> 
> slauncha...@gmail.com | @SlaunchaMan | jeffkelley.org
> 
>> On Apr 13, 2017, at 8:19 AM, David Sweeris via swift-evolution 
>>  wrote:
>> 
>>> 
>>> On Apr 13, 2017, at 3:56 AM, Andrew Hart via swift-evolution 
>>>  wrote:
>>> 
>>> Recently I’ve been considering the lack of safety around array indexes. 
>>> Swift is designed with safety in mind, so this example would not compile:
>>> 
>>> var myString: String? = “hello”
>>> myString.append(“ world!”)
>>> 
>>> The string is optional, not guaranteed to exist, so the last line requires 
>>> a “!” to force-unwrap it.
>>> 
>>> 
>>> 
>>> public func tableView(_ tableView: UITableView, numberOfRowsInSection 
>>> section: Int) -> Int {
>>> let section = self.sections[section]
>>> 
>>> return section.items.count
>>> }
>>> 
>>> In this example, we could provide a section number that goes beyond the 
>>> bounds of the self.sections array, without any warning.
>>> 
>>> My suggestion is perhaps arrays should by default return an optional when 
>>> given an index, and of course they’d support forced-unwrapping too. So you 
>>> could then do this:
>>> 
>>> let section = self.sections[section]
>>> if section == nil {
>>> return 0
>>> } else {
>>> return section!.items.count
>>> }
>>> 
>>> Or you could do this:
>>> 
>>> let section = self.sections[section]!
>>> 
>>> return section.items.count
>>> 
>>> Of course this would be less convenient in a lot of cases, but this is the 
>>> 1 place where apps seem to encounter a crash, crashing for the same reason 
>>> that’s especially avoided across most of the rest of Swift.
>> 
>> My understanding is that we need the current behavior to meet performance 
>> goals. We’ve discussed adding a “safe” subscript before, but the discussion 
>> usually fizzles out when no clear winner for the argument label emerges.
>> 
>> - 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

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


[swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Bas Thomas Broek via swift-evolution
This has been proposed before. The current implementation is intentional, as 
seen on the swift-evolution repo: 
https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md#strings-characters-and-collection-types
 
.
 This is why: 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002446.html

> Recently I’ve been considering the lack of safety around array indexes. Swift 
> is designed with safety in mind, so this example would not compile:
> 
> var myString: String? = “hello”
> myString.append(“ world!”)
> 
> The string is optional, not guaranteed to exist, so the last line requires a 
> “!” to force-unwrap it.
> 
> 
> 
> public func tableView(_ tableView: UITableView, numberOfRowsInSection 
> section: Int) ->Int {
> let section = self.sections[section]
> 
> return section.items.count
> }
> 
> In this example, we could provide a section number that goes beyond the 
> bounds of the self.sections array, without any warning.
> 
> My suggestion is perhaps arrays should by default return an optional when 
> given an index, and of course they’d support forced-unwrapping too. So you 
> could then do this:
> 
> let section = self.sections[section]
> if section == nil {
> return 0
> } else {
> return section!.items.count
> }
> 
> Or you could do this:
> 
> let section = self.sections[section]!
> 
> return section.items.count
> 
> 
> 
> Of course this would be less convenient in a lot of cases, but this is the 1 
> place where apps seem to encounter a crash, crashing for the same reason 
> that’s especially avoided across most of the rest of 
> Swift.___
> 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] [Review] SE-0166: Swift Archival & Serialization

2017-04-13 Thread Johannes Lund via swift-evolution
This might be too late, but anyway:

> What is your evaluation of the proposal?
Unsure. For archival purposes/NSCoding replacement this seems great. As the 
best way to do decode JSON from external APIs I find it at least to be very 
unconvincing. But then, I’m not sure if this is a goal of the proposal.


> Is the problem being addressed significant enough to warrant a change to 
> Swift?
I don’t know.


> Does this proposal fit well with the feel and direction of Swift?
To me the proposed implementation doesn’t seem particularly elegant or Swifty.

> If you have used other languages or libraries with a similar feature, how do 
> you feel that this proposal compares to those?

(Assuming decoding JSON from external APIs is a goal)
>From creating and maintaining the Decodable 
> library I learned:
- There are lots of weird APIs out there, that ultimately should be simple to 
support (e.g how optional values are described, bools as strings, 1-length 
arrays represented without the wrapping array, etc, etc). This proposal doesn’t 
talk about these kinds of problems (I don’t even see an optional property in an 
example), and I haven’t been able to get a sense of whether they are solvable 
or not with the proposed implementation, which I do not fully understand.
- Good error messages (with like backtraces) are important when writing lots of 
of decoding code by hand. I see no mentions of error messages in these 
proposals. Swift-Error breakpoints, could be a solution, but from my experience 
it’s not really feasible.


> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?
Several quick readings and quite a bit of thinking. I am really confused by 
these proposals though.

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Ricardo Parada via swift-evolution
That would be good, I think because it would force everyone to be precise in 
regards to trailing whitespace.  And I don't see that as a bad thing.


> On Apr 13, 2017, at 9:54 AM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> I was really confused by your last reply. Actually I’ve got a better idea for 
> a fix-it. :-)
> 
> let str_8 = """↵  
> foo··↵
> """
> warning: line # includes trailing space characters in multi-line string 
> literal
>   foo··
>  ~~  
>   Fix-it: Insert "\n\" (after these space characters)
> The fix-it will inset \n\ after all your space characters, so the developer 
> is kinda forced to strip them manually to foo or let the IDE add \n\ if 
> he really needs that precision.
> 
> That would work. :)
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 13. April 2017 um 15:46:52, John Holdsworth (m...@johnholdsworth.com 
> ) schrieb:
> 
>> \n\
>> would work
>> 
>>> On 13 Apr 2017, at 14:44, John Holdsworth >> > wrote:
>>> 
>>> 
>>> I’ve never understood how you mean "explicit backslash". backslash has 
>>> specific roles
>>> and at the moment it is assigned to meaning standard escapes or "don’t 
>>> include this next
>>> newline in the literal". I can’t see how it could be reassigned to mean 
>>> “include whitespace”
>>> without loosing the option to concatenate lines.
>>> 
>>> fix-its are beyond my pay grade so that’ll have to wait until Apple looks 
>>> at the implementation!
>>> 
>>> 
 On 13 Apr 2017, at 14:32, Adrian Zubarev > wrote:
 
 A warning that will popup when you included any trailing spaces in a 
 ‘content line’ without the explicit backslash could also provide a fix-it 
 to the user to remove these spaces. However if you can emit that warning 
 and calculate the spaces to remove, than the compiler should be able to 
 swallow these characters by default right?
 
 
>>> 
>> 
> 
> 
> ___
> 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] [Pitch] Adding safety to arrays

2017-04-13 Thread Jeff Kelley via swift-evolution
Apologies if this has been suggested before, but going off of Andrew’s message, 
a simple syntax could be to use our existing Optional syntax:

let array = ["foo", "bar", "baz"]

let first = array[0] // type is `String`
let third = array[2?] // type is `String?`, value is .some("baz")
let fourth = array[3?] // type is `String?`, value is .none

Jeff Kelley

slauncha...@gmail.com | @SlaunchaMan  | 
jeffkelley.org 
> On Apr 13, 2017, at 8:19 AM, David Sweeris via swift-evolution 
>  wrote:
> 
>> 
>> On Apr 13, 2017, at 3:56 AM, Andrew Hart via swift-evolution 
>> > wrote:
>> 
>> Recently I’ve been considering the lack of safety around array indexes. 
>> Swift is designed with safety in mind, so this example would not compile:
>> 
>> var myString: String? = “hello”
>> myString.append(“ world!”)
>> 
>> The string is optional, not guaranteed to exist, so the last line requires a 
>> “!” to force-unwrap it.
>> 
>> 
>> 
>> public func tableView(_ tableView: UITableView, numberOfRowsInSection 
>> section: Int) -> Int {
>> let section = self.sections[section]
>> 
>> return section.items.count
>> }
>> 
>> In this example, we could provide a section number that goes beyond the 
>> bounds of the self.sections array, without any warning.
>> 
>> My suggestion is perhaps arrays should by default return an optional when 
>> given an index, and of course they’d support forced-unwrapping too. So you 
>> could then do this:
>> 
>> let section = self.sections[section]
>> if section == nil {
>> return 0
>> } else {
>> return section!.items.count
>> }
>> 
>> Or you could do this:
>> 
>> let section = self.sections[section]!
>> 
>> return section.items.count
>> 
>> Of course this would be less convenient in a lot of cases, but this is the 1 
>> place where apps seem to encounter a crash, crashing for the same reason 
>> that’s especially avoided across most of the rest of Swift.
> 
> My understanding is that we need the current behavior to meet performance 
> goals. We’ve discussed adding a “safe” subscript before, but the discussion 
> usually fizzles out when no clear winner for the argument label emerges.
> 
> - 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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
I was really confused by your last reply. Actually I’ve got a better idea for a 
fix-it. :-)

let str_8 = """↵  
foo··↵
"""
warning: line # includes trailing space characters in multi-line string literal
  foo··
 ~~  
  Fix-it: Insert "\n\" (after these space characters)
The fix-it will inset \n\ after all your space characters, so the developer is 
kinda forced to strip them manually to foo or let the IDE add \n\ if he 
really needs that precision.

That would work. :)



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 15:46:52, John Holdsworth (m...@johnholdsworth.com) 
schrieb:

\n\
would work

On 13 Apr 2017, at 14:44, John Holdsworth  wrote:


I’ve never understood how you mean "explicit backslash". backslash has specific 
roles
and at the moment it is assigned to meaning standard escapes or "don’t include 
this next
newline in the literal". I can’t see how it could be reassigned to mean 
“include whitespace”
without loosing the option to concatenate lines.

fix-its are beyond my pay grade so that’ll have to wait until Apple looks at 
the implementation!


On 13 Apr 2017, at 14:32, Adrian Zubarev  
wrote:

A warning that will popup when you included any trailing spaces in a ‘content 
line’ without the explicit backslash could also provide a fix-it to the user to 
remove these spaces. However if you can emit that warning and calculate the 
spaces to remove, than the compiler should be able to swallow these characters 
by default right?




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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
The result is not surprisingly to me, at least not if I follow the simplicity 
of my gist.

"Line 1Line2"

Notice I put quotes around the string to better showcase the result here in the 
mailing list.

The backslash serves two jobs in lines s0 to s(n - 1):

Disable new line injection.
Trailing space precision.
The backslash serves only one job for the line sn (or as I also refer it as 
‘last content line’):

Trailing space precision.
Here some other example:

"""
Line 1···\n\
Line 2··\
"""
Result:

"Line 1···\nLine 2··"

Another one:

"""
Line 1···\n\
Line 2·
"""
Result:

"Line 1···\nLine 2"

The second line cannot and should not contain · because 
right (trailing) precision is handled by the backslash, where left (leading) 
precision is handled by the indent stripping algorithm calculated from the 
indent prefix before the closing delimiter """.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 15:29:52, Ricardo Parada (rpar...@mac.com) schrieb:

I don't care much for trailing whitespace but I thought we should respect the 
trailing whitespace in the event that it is significant.  

If I'm worried about precision in a string, I turn on the display of whitespace 
characters and make sure everything is as expected.  

I also think it would surprise me if I put a space there and then the compiler 
removes it.

Also, what would this mean?

"""
Line 1    \
Line 2
"""

Is that backslash escaping the newline? or is it there to include the trailing 
whitespace on Line 1?  


On Apr 13, 2017, at 9:20 AM, Adrian Zubarev  
wrote:

This is not an assumptions but a fact that the trailing spaces cannot and 
should not exist without an explicit annotation for precision, otherwise the 
backslash looses one of its main and significant functionality.




-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 15:13:50, Ricardo Parada (rpar...@mac.com) schrieb:

Hi Adrian,

My conclusion that we should leave it alone is based on the assumption that 
someone may consider the trailing whitespace significant and correct.


On Apr 13, 2017, at 9:05 AM, Adrian Zubarev  
wrote:

That would be so wrong, because it’s not obvious to anyone how long your string 
will be.

"""
foo
"""
I could tell you, that the string from above could have 10k characters, even if 
you wouldn’t believe me, as it was proposed (and included in yesterday’s 
toolchain) my claim can be true.

The trailing spaces needs to be stripped by the algorithm unless there is an 
explicit precision annotation with a backslash!

"""
foo   \
"""
That example definitely won’t have 10k characters.




-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com) schrieb:

Trailing whitespace 

You also propose to remove trailing white space in each line unless the 
whitespace is followed by a backslash.   For example:
let str_2 = """↵ 
foo··↵
"""
The two trailing whitespaces after foo would get removed according to what you 
are proposing. I don't like this rule. I think we are better off with leaving 
it alone and to the tools as Brent suggested. 



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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Theoretically that would be enough and lightweight solution to that problem, I 
could live with that. Optimally stripping them automatically would be ideal, 
however I cannot tell how complicated this might be to implement.

A warning that will popup when you included any trailing spaces in a ‘content 
line’ without the explicit backslash could also provide a fix-it to the user to 
remove these spaces. However if you can emit that warning and calculate the 
spaces to remove, than the compiler should be able to swallow these characters 
by default right?

let s1 = """↵
content·⇥···⇥··⇥↵


s1 == "content" // => true
The warning itself could bite with Xcode, it depends on who’s faster to precede 
that problem. Either Xcode will strip them for you (but designing the literal 
we should not rely on that), or the compiler will emit the warning followed by 
Xcode which will strip them, which removes the warning. This would be kind of 
silly right?



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 15:10:36, John Holdsworth (m...@johnholdsworth.com) 
schrieb:

Hi Adrian,

Would you settle for a warning for trailing whitespace in a literal?
Removing it is a bit fiddly to implement and I’m not sure it’s a feature.

John


On 13 Apr 2017, at 14:05, Adrian Zubarev via swift-evolution 
 wrote:

That would be so wrong, because it’s not obvious to anyone how long your string 
will be.

"""
foo
"""
I could tell you, that the string from above could have 10k characters, even if 
you wouldn’t believe me, as it was proposed (and included in yesterday’s 
toolchain) my claim can be true.

The trailing spaces needs to be stripped by the algorithm unless there is an 
explicit precision annotation with a backslash!

"""
foo   \
"""
That example definitely won’t have 10k characters.




-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com) schrieb:

Trailing whitespace 

You also propose to remove trailing white space in each line unless the 
whitespace is followed by a backslash.   For example:
let str_2 = """↵
foo··↵
"""
The two trailing whitespaces after foo would get removed according to what you 
are proposing. I don't like this rule. I think we are better off with leaving 
it alone and to the tools as Brent suggested. 

___
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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Ricardo Parada via swift-evolution
I don't care much for trailing whitespace but I thought we should respect the 
trailing whitespace in the event that it is significant.  

If I'm worried about precision in a string, I turn on the display of whitespace 
characters and make sure everything is as expected.  

I also think it would surprise me if I put a space there and then the compiler 
removes it.

Also, what would this mean?

"""
Line 1\
Line 2
"""

Is that backslash escaping the newline? or is it there to include the trailing 
whitespace on Line 1?  


> On Apr 13, 2017, at 9:20 AM, Adrian Zubarev  
> wrote:
> 
> This is not an assumptions but a fact that the trailing spaces cannot and 
> should not exist without an explicit annotation for precision, otherwise the 
> backslash looses one of its main and significant functionality.
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 13. April 2017 um 15:13:50, Ricardo Parada (rpar...@mac.com 
> ) schrieb:
> 
>> Hi Adrian,
>> 
>> My conclusion that we should leave it alone is based on the assumption that 
>> someone may consider the trailing whitespace significant and correct.
>> 
>> 
>>> On Apr 13, 2017, at 9:05 AM, Adrian Zubarev 
>>> > 
>>> wrote:
>>> 
>>> That would be so wrong, because it’s not obvious to anyone how long your 
>>> string will be.
>>> 
>>> """
>>> foo
>>> """
>>> I could tell you, that the string from above could have 10k characters, 
>>> even if you wouldn’t believe me, as it was proposed (and included in 
>>> yesterday’s toolchain) my claim can be true.
>>> 
>>> The trailing spaces needs to be stripped by the algorithm unless there is 
>>> an explicit precision annotation with a backslash!
>>> 
>>> """
>>> foo   \
>>> """
>>> That example definitely won’t have 10k characters.
>>> 
>>> 
>>> 
>>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com 
>>> ) schrieb:
>>> 
 Trailing whitespace 
 
 You also propose to remove trailing white space in each line unless the 
 whitespace is followed by a backslash.   For example:
 let str_2 = """↵
 foo··↵
 """
 The two trailing whitespaces after foo would get removed according to what 
 you are proposing. I don't like this rule. I think we are better off with 
 leaving it alone and to the tools as Brent suggested. 
>>> 
>> 
> 
> 

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Gwendal Roué via swift-evolution
Doesn't the principle of least surprise applies here?

In most other languages, the final \n is implicit in multi-line strings and 
heredocs: I think """↵foo↵foo↵" should be equal to "foo\nfoo\n", because this 
is what most developers will assume.

Yes it will not play well with the standard print() function. Swift is 
discovering that being as handy as a scripting language is not an easy task. 
But the problem lies in all the printing / stdout / stderr API, not in the 
string literals.

Gwendal Roué

> Le 13 avr. 2017 à 15:17, Adrian Zubarev via swift-evolution 
>  a écrit :
> 
> As already mentioned I revised my opinion about the last content line, 
> because the model I summarized mimics perfectly how you’d write text 
> paragraphs. 
> 
> I’d say most of the time string concatenation is used to combine strings on 
> the same line. A string literal however should only represent the content 
> between the delimiters. Including an implicit new line for the last content 
> line might seem consistent to other content lines from s0 to s(n - 1) (I 
> refer to my gist here), but it should be consistent to the standard string 
> literal instead. 
> 
> print("""
> foo
> foo
> """)
> That will only print
> 
> foo
> foo
> As expected (I don’t take the new line from print into account). That is the 
> natural an consistent way.
> 
> If you’d need a new line at the end you’ll have natural ways of doing so, or 
> you can fallback to the explicit \n character.
> 
> print("""
> foo
> foo\n
> """)
>  
> // Equivalent to the print above this comment, because the backslash
> // in the last line only serves precision, but has no effect on the  
> // implicit new line character, because the last line doesn't add any.
> print("""
> foo
> foo\n\
> """)
> 
> // Natural text way
> print("""
> foo
> foo
>  
> """)
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com 
> ) schrieb:
> 
>> Trailing newline 
>> 
>> We need consensus on whether the trailing newline on the last line should be 
>> included.  You are proposing it should not be included which will add an 
>> empty line to Brent's xml concatenation example. The example looks better 
>> when the trailing newline is included. 
>> 
>> In the more rare case where the newline is not desired on the last line then 
>> you can just include the backslash at the end. See Brent's revised proposal: 
>> https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>>  
>> 
> 
> ___
> 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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
This is not an assumptions but a fact that the trailing spaces cannot and 
should not exist without an explicit annotation for precision, otherwise the 
backslash looses one of its main and significant functionality.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 15:13:50, Ricardo Parada (rpar...@mac.com) schrieb:

Hi Adrian,

My conclusion that we should leave it alone is based on the assumption that 
someone may consider the trailing whitespace significant and correct.


On Apr 13, 2017, at 9:05 AM, Adrian Zubarev  
wrote:

That would be so wrong, because it’s not obvious to anyone how long your string 
will be.

"""
foo
"""
I could tell you, that the string from above could have 10k characters, even if 
you wouldn’t believe me, as it was proposed (and included in yesterday’s 
toolchain) my claim can be true.

The trailing spaces needs to be stripped by the algorithm unless there is an 
explicit precision annotation with a backslash!

"""
foo   \
"""
That example definitely won’t have 10k characters.




-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com) schrieb:

Trailing whitespace 

You also propose to remove trailing white space in each line unless the 
whitespace is followed by a backslash.   For example:
let str_2 = """↵
foo··↵
"""
The two trailing whitespaces after foo would get removed according to what you 
are proposing. I don't like this rule. I think we are better off with leaving 
it alone and to the tools as Brent suggested. 

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
As already mentioned I revised my opinion about the last content line, because 
the model I summarized mimics perfectly how you’d write text paragraphs.

I’d say most of the time string concatenation is used to combine strings on the 
same line. A string literal however should only represent the content between 
the delimiters. Including an implicit new line for the last content line might 
seem consistent to other content lines from s0 to s(n - 1) (I refer to my gist 
here), but it should be consistent to the standard string literal instead.

print("""
foo
foo
""")
That will only print

foo
foo
As expected (I don’t take the new line from print into account). That is the 
natural an consistent way.

If you’d need a new line at the end you’ll have natural ways of doing so, or 
you can fallback to the explicit \n character.

print("""
foo
foo\n
""")
 
// Equivalent to the print above this comment, because the backslash
// in the last line only serves precision, but has no effect on the  
// implicit new line character, because the last line doesn't add any.
print("""
foo
foo\n\
""")

// Natural text way
print("""
foo
foo
 
""")


-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com) schrieb:

Trailing newline 

We need consensus on whether the trailing newline on the last line should be 
included.  You are proposing it should not be included which will add an empty 
line to Brent's xml concatenation example. The example looks better when the 
trailing newline is included. 

In the more rare case where the newline is not desired on the last line then 
you can just include the backslash at the end. See Brent's revised proposal: 
https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Ricardo Parada via swift-evolution
Hi Adrian,

My conclusion that we should leave it alone is based on the assumption that 
someone may consider the trailing whitespace significant and correct.


> On Apr 13, 2017, at 9:05 AM, Adrian Zubarev  
> wrote:
> 
> That would be so wrong, because it’s not obvious to anyone how long your 
> string will be.
> 
> """
> foo
> """
> I could tell you, that the string from above could have 10k characters, even 
> if you wouldn’t believe me, as it was proposed (and included in yesterday’s 
> toolchain) my claim can be true.
> 
> The trailing spaces needs to be stripped by the algorithm unless there is an 
> explicit precision annotation with a backslash!
> 
> """
> foo   \
> """
> That example definitely won’t have 10k characters.
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com 
> ) schrieb:
> 
>> Trailing whitespace 
>> 
>> You also propose to remove trailing white space in each line unless the 
>> whitespace is followed by a backslash.   For example:
>> let str_2 = """↵   
>> foo··↵
>> """
>> The two trailing whitespaces after foo would get removed according to what 
>> you are proposing. I don't like this rule. I think we are better off with 
>> leaving it alone and to the tools as Brent suggested. 
> 

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
That would be so wrong, because it’s not obvious to anyone how long your string 
will be.

"""
foo
"""
I could tell you, that the string from above could have 10k characters, even if 
you wouldn’t believe me, as it was proposed (and included in yesterday’s 
toolchain) my claim can be true.

The trailing spaces needs to be stripped by the algorithm unless there is an 
explicit precision annotation with a backslash!

"""
foo   \
"""
That example definitely won’t have 10k characters.



-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 14:35:59, Ricardo Parada (rpar...@mac.com) schrieb:

Trailing whitespace 

You also propose to remove trailing white space in each line unless the 
whitespace is followed by a backslash.   For example:
let str_2 = """↵   
foo··↵
"""
The two trailing whitespaces after foo would get removed according to what you 
are proposing. I don't like this rule. I think we are better off with leaving 
it alone and to the tools as Brent suggested. 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Question: What is the benefit of disabling the indent stripping? I’m not even 
sure what I should imagine when I read “if the indent stripping is enabled”.

My mental model is simple, the compiler looks for line where the closing 
tripled delimiter is. Takes all space characters in between the start of the 
line and the delimiter (there cannot be any other character at all), and makes 
it as the indent prefix for all content lines s0 to sn. This is simple and does 
not require an essay of rules to support that.

That said, the indent stripping algorithm is always enabled, except when the 
indent prefix is an empty string "".

It’s far more simpler to teach the two different types of the multi-line string 
literal, rather then allowing string content after the starting delimiter and 
than explaining why the literal does not inject a new line if you happen to 
write

"""
foo
bar
"""
Instead of:

"""foo
bar
"""
This approach also eliminates the implication of the existence of:

"""
foo
bar"""


-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 14:41:45, Brent Royal-Gordon (br...@architechies.com) 
schrieb:

On Apr 13, 2017, at 5:35 AM, Ricardo Parada via swift-evolution 
 wrote:

Take a look at Brent's revised proposal.I personally thin it is perfect.  Take 
a look:

https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md

Well, um, looks like we got scooped. (I was playing with some non-essential 
wording and trying to test all the examples before I pointed the list at the 
new version.)

Since requiring a leading backslash went over like a lead balloon, we've 
revised the proposal one more time. The leading newline is now optional: If 
indentation stripping is enabled, you can either start typing content on the 
same line as the delimiter, or you can start on the next line. I resisted this 
solution for a while because it seems ad-hoc, but ultimately it's the design 
that preserves the most formatting flexibility for the user, so I think it's 
the right way to go.

Other than that, there are no changes to the design in this revision, though 
I've rephrased a few things and added a section about why we strip a leading 
newline but not a trailing one.

John has also built a new version of the toolchain which matches this behavior. 
Download it here: http://johnholdsworth.com/swift-LOCAL-2017-04-13-a-osx.tar.gz

Thanks for your feedback!

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Ricardo Parada via swift-evolution
I think it's solid and thorough.  I think it's winner.


> On Apr 13, 2017, at 8:41 AM, Brent Royal-Gordon  
> wrote:
> 
>> On Apr 13, 2017, at 5:35 AM, Ricardo Parada via swift-evolution 
>> > wrote:
>> 
>> Take a look at Brent's revised proposal.I personally thin it is perfect.  
>> Take a look:
>> 
>> https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>>  
>> 
> Well, um, looks like we got scooped. (I was playing with some non-essential 
> wording and trying to test all the examples before I pointed the list at the 
> new version.)
> 
> Since requiring a leading backslash went over like a lead balloon, we've 
> revised the proposal one more time. The leading newline is now optional: If 
> indentation stripping is enabled, you can either start typing content on the 
> same line as the delimiter, or you can start on the next line. I resisted 
> this solution for a while because it seems ad-hoc, but ultimately it's the 
> design that preserves the most formatting flexibility for the user, so I 
> think it's the right way to go.
> 
> Other than that, there are no changes to the design in this revision, though 
> I've rephrased a few things and added a section about why we strip a leading 
> newline but not a trailing one.
> 
> John has also built a new version of the toolchain which matches this 
> behavior. Download it here: 
> http://johnholdsworth.com/swift-LOCAL-2017-04-13-a-osx.tar.gz 
> 
> 
> Thanks for your feedback!
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread John Holdsworth via swift-evolution
 Thanks again Brent. This version looks great! I think we’re really getting 
there.

> On 13 Apr 2017, at 13:41, Brent Royal-Gordon via swift-evolution 
>  wrote:
> 
>> On Apr 13, 2017, at 5:35 AM, Ricardo Parada via swift-evolution 
>> > wrote:
>> 
>> Take a look at Brent's revised proposal.I personally thin it is perfect.  
>> Take a look:
>> 
>> https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>>  
>> 
> Well, um, looks like we got scooped. (I was playing with some non-essential 
> wording and trying to test all the examples before I pointed the list at the 
> new version.)
> 
> Since requiring a leading backslash went over like a lead balloon, we've 
> revised the proposal one more time. The leading newline is now optional: If 
> indentation stripping is enabled, you can either start typing content on the 
> same line as the delimiter, or you can start on the next line. I resisted 
> this solution for a while because it seems ad-hoc, but ultimately it's the 
> design that preserves the most formatting flexibility for the user, so I 
> think it's the right way to go.
> 
> Other than that, there are no changes to the design in this revision, though 
> I've rephrased a few things and added a section about why we strip a leading 
> newline but not a trailing one.
> 
> John has also built a new version of the toolchain which matches this 
> behavior. Download it here: 
> http://johnholdsworth.com/swift-LOCAL-2017-04-13-a-osx.tar.gz 
> 
> 
> Thanks for your feedback!
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 
> ___
> 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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Brent Royal-Gordon via swift-evolution
> On Apr 13, 2017, at 5:35 AM, Ricardo Parada via swift-evolution 
>  wrote:
> 
> Take a look at Brent's revised proposal.I personally thin it is perfect.  
> Take a look:
> 
> https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>  
> 
Well, um, looks like we got scooped. (I was playing with some non-essential 
wording and trying to test all the examples before I pointed the list at the 
new version.)

Since requiring a leading backslash went over like a lead balloon, we've 
revised the proposal one more time. The leading newline is now optional: If 
indentation stripping is enabled, you can either start typing content on the 
same line as the delimiter, or you can start on the next line. I resisted this 
solution for a while because it seems ad-hoc, but ultimately it's the design 
that preserves the most formatting flexibility for the user, so I think it's 
the right way to go.

Other than that, there are no changes to the design in this revision, though 
I've rephrased a few things and added a section about why we strip a leading 
newline but not a trailing one.

John has also built a new version of the toolchain which matches this behavior. 
Download it here: http://johnholdsworth.com/swift-LOCAL-2017-04-13-a-osx.tar.gz

Thanks for your feedback!

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Ricardo Parada via swift-evolution
Oops, my apologies for misspelling your name.  It was a typo.

> On Apr 13, 2017, at 8:35 AM, Ricardo Parada via swift-evolution 
>  wrote:
> 
> Adriam
> 
> Take a look at Brent's revised proposal.I personally thin it is perfect.  
> Take a look:
> 
> https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>  
> 
> 
> 
> Regarding what you are proposing:
> 
> Trailing newline 
> 
> We need consensus on whether the trailing newline on the last line should be 
> included.  You are proposing it should not be included which will add an 
> empty line to Brent's xml concatenation example. The example looks better 
> when the trailing newline is included. 
> 
> In the more rare case where the newline is not desired on the last line then 
> you can just include the backslash at the end. See Brent's revised proposal: 
> https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>  
> 
> 
> Trailing whitespace 
> 
> You also propose to remove trailing white space in each line unless the 
> whitespace is followed by a backslash.   For example:
> let str_2 = """↵  
> foo··↵
> """
> The two trailing whitespaces after foo would get removed according to what 
> you are proposing. I don't like this rule. I think we are better off with 
> leaving it alone and to the tools as Brent suggested. 
> 
> Regards,
> Ricardo Parada
> 
> 
> 
> 
> On Apr 13, 2017, at 5:28 AM, Adrian Zubarev via swift-evolution 
> > wrote:
> 
>> Now that I had some sleep I actually revise my opinion about the last line. 
>> I took a few hours to sum my thoughts together in a gist, here is a 
>> formatted version of it: 
>> https://gist.github.com/DevAndArtist/dae76d4e3d4e49b1fab22ef7e86a87a9 
>> 
>> Simple ‘multi-line string literal’ model
>> 
>> Core features:
>> 
>> Omitting of (most) backslashes for ".
>> Altering the string with implicit new line injection at the end of the line.
>> Consequences of #1:
>> 
>> To omit escaping the quote character, the delimiter characters for the 
>> multi-line string literal will be tripled quotes """, also similar to other 
>> programming languages.
>> 
>> When a standard string literal contains at least 5 quotes, then the usage of 
>> a multi-line string literal will be shorter.
>> 
>> ""// With escapes
>> ""  // With tripled 
>> literals
>> Consequences of #2:
>> 
>> To fully support this feature, we need to compromise the design for 
>> simplicity and intuitivity.
>> 
>> This feature needs precision for leading and trailing spaces.
>> Alternatively one would need a way to disable new line injection to also 
>> support code formatting.
>> Two ways of writing a multi-line string literal:
>> 
>> Single line version """abc""" is trivial and already was shown above.
>> 
>> The multi-line version comes with a few compromises for simplicity of rules:
>> 
>> """   // DS (delimiter start)
>> foo   // s0
>> foo   // s1
>> foo   // s2
>> """   // DE (delimiter end)
>> The string content is always written between the lines DS and DE (delimiter 
>> lines). 
>> 
>> To not to go the continuation quotes path, the left (or leading) precision 
>> is handled by the closing delimiter (1. compromise). The closing delimiter 
>> is also responsible for the indent algorithm, which will calculate the 
>> stripping prefix in line DE and apply stripping to lines s0 to sn.
>> 
>> Right (or trailing) precision of each line from s0 to sn (notice n equals 2 
>> in the example above) is handled by a backslash character (2. compromise).
>> 
>> The right precision comes at a price of losing the implicit new line 
>> injection, however this was also a requested feature (3. compromise). That 
>> means that the backslash serves two jobs simultaneously.
>> 
>> New line injection happens only on lines s0 to s(n - 1) (4. and last 
>> compromise of the design). The last line sn (or s2 above) does not inject a 
>> new line into the final string. This implies that in this line a backslash 
>> character handles only right precision, or one could say it’s reduced to one 
>> functionality.
>> 
>> Important:
>> 
>> Because whitespace is important to these examples, it is explicitly 
>> indicated: · is a space, ⇥ is a tab, and ↵ is a newline.
>> 
>> Leading/trailing precision and indent (1. and 2. compromise):
>> 
>> // Nothing to strip in this example (no ident).
>> let str_1 = """↵  
>> foo↵
>> """
>> 
>> // No right precision (no backslash) -> whitespaces will be stripped.
>> let str_2 = """↵  
>> foo··↵
>> """
>> 
>> // Same as `str_2`
>> let str_3 = """↵  
>> foo↵
>> """
>> 
>> // 

Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Ricardo Parada via swift-evolution
Adriam

Take a look at Brent's revised proposal.I personally thin it is perfect.  Take 
a look:

https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md


Regarding what you are proposing:

Trailing newline 

We need consensus on whether the trailing newline on the last line should be 
included.  You are proposing it should not be included which will add an empty 
line to Brent's xml concatenation example. The example looks better when the 
trailing newline is included. 

In the more rare case where the newline is not desired on the last line then 
you can just include the backslash at the end. See Brent's revised proposal: 
https://github.com/johnno1962a/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md

Trailing whitespace 

You also propose to remove trailing white space in each line unless the 
whitespace is followed by a backslash.   For example:
let str_2 = """↵  
foo··↵
"""
The two trailing whitespaces after foo would get removed according to what you 
are proposing. I don't like this rule. I think we are better off with leaving 
it alone and to the tools as Brent suggested. 

Regards,
Ricardo Parada




On Apr 13, 2017, at 5:28 AM, Adrian Zubarev via swift-evolution 
> wrote:

> Now that I had some sleep I actually revise my opinion about the last line. I 
> took a few hours to sum my thoughts together in a gist, here is a formatted 
> version of it: 
> https://gist.github.com/DevAndArtist/dae76d4e3d4e49b1fab22ef7e86a87a9 
> 
> Simple ‘multi-line string literal’ model
> 
> Core features:
> 
> Omitting of (most) backslashes for ".
> Altering the string with implicit new line injection at the end of the line.
> Consequences of #1:
> 
> To omit escaping the quote character, the delimiter characters for the 
> multi-line string literal will be tripled quotes """, also similar to other 
> programming languages.
> 
> When a standard string literal contains at least 5 quotes, then the usage of 
> a multi-line string literal will be shorter.
> 
> ""// With escapes
> ""  // With tripled 
> literals
> Consequences of #2:
> 
> To fully support this feature, we need to compromise the design for 
> simplicity and intuitivity.
> 
> This feature needs precision for leading and trailing spaces.
> Alternatively one would need a way to disable new line injection to also 
> support code formatting.
> Two ways of writing a multi-line string literal:
> 
> Single line version """abc""" is trivial and already was shown above.
> 
> The multi-line version comes with a few compromises for simplicity of rules:
> 
> """   // DS (delimiter start)
> foo   // s0
> foo   // s1
> foo   // s2
> """   // DE (delimiter end)
> The string content is always written between the lines DS and DE (delimiter 
> lines).
> 
> To not to go the continuation quotes path, the left (or leading) precision is 
> handled by the closing delimiter (1. compromise). The closing delimiter is 
> also responsible for the indent algorithm, which will calculate the stripping 
> prefix in line DE and apply stripping to lines s0 to sn.
> 
> Right (or trailing) precision of each line from s0 to sn (notice n equals 2 
> in the example above) is handled by a backslash character (2. compromise).
> 
> The right precision comes at a price of losing the implicit new line 
> injection, however this was also a requested feature (3. compromise). That 
> means that the backslash serves two jobs simultaneously.
> 
> New line injection happens only on lines s0 to s(n - 1) (4. and last 
> compromise of the design). The last line sn (or s2 above) does not inject a 
> new line into the final string. This implies that in this line a backslash 
> character handles only right precision, or one could say it’s reduced to one 
> functionality.
> 
> Important:
> 
> Because whitespace is important to these examples, it is explicitly 
> indicated: · is a space, ⇥ is a tab, and ↵ is a newline.
> 
> Leading/trailing precision and indent (1. and 2. compromise):
> 
> // Nothing to strip in this example (no ident).
> let str_1 = """↵  
> foo↵
> """
> 
> // No right precision (no backslash) -> whitespaces will be stripped.
> let str_2 = """↵  
> foo··↵
> """
> 
> // Same as `str_2`
> let str_3 = """↵  
> foo↵
> """
> 
> // Line `DE` of the closing delimiter calculates the indent prefix  
> // `··` and strips it from `s0` (left precision).
> let str_4 = """↵  
> ··foo↵
> ··"""
> 
> // Line `DE` of the closing delimiter calculates the indent prefix  
> // `` and strips it from `s0` (left precision).
> // No right precision (no backslash) -> whitespaces will be stripped.
> let str_5 = """↵  
> foo··↵
> """
> 
> // Line `DE` of the closing delimiter calculates the indent prefix  
> // `⇥ ⇥ ` and strips it from `s0` (left precision).
> // Right precision is applied 

Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Thorsten Seitz via swift-evolution

> Am 13.04.2017 um 00:20 schrieb Brent Royal-Gordon :
> 
> Wow, maybe I shouldn't have slept.

:-)

> 
> Okay, let's deal with trailing newline first. I'm *very* confident that 
> trailing newlines should be kept by default. This opinion comes from lots of 
> practical experience with multiline string features in other languages. In 
> practice, if you're generating files in a line-oriented way, you're usually 
> generating them a line at a time. It's pretty rare that you want to generate 
> half a line and then add more to it in another statement; it's more likely 
> you'll interpolate the data. I'm not saying it doesn't happen, of course, but 
> it happens a lot less often than you would think just sitting by the fire, 
> drinking whiskey and musing over strings.
> 
> I know that, if you're pushing for this feature, it's not satisfying to have 
> the answer be "trust me, it's not what you want". But trust me, it's not what 
> you want.
> 
> Moving to the other end, I think we could do a leading newline strip *if* 
> we're willing to create multiline and non-multiline modes—that is, newlines 
> are _not allowed at all_ unless the opening delimiter ends its line and the 
> closing delimiter starts its line (modulo indentation). But I'm reluctant to 
> do that because, well, it's weird and complicated. I also get the feeling 
> that, if there's a single-line mode and a multi-line mode, we ought to treat 
> them as truly orthogonal features and allow `"`-delimited strings to use 
> multi-line mode, but I'm really not convinced that's a good idea.
> 
> (Note, by the way, that heredocs—a *really* common multiline string 
> design—always strip the leading newline but not the trailing one.)
> 
> Adrian cited this example, where I agree that you really don't want the 
> string to be on the same line as the leading delimiter:
> 
>   let myReallyLongXMLConstantName = """
>
>   
>  John Doe
>  XML Developer's 
> Guide
>  Computer
>  44.95
>   
>\
>"""
> 
> But there are lots of places where it works fine. Is there a good reason to 
> force an additional newline in this?
> 
>   case .isExprSameType(let from, let to):
>   return """checking a value with optional type 
> \(from) against dynamic type \(to) \
> succeeds whenever the value is 
> non-'nil'; did you mean to use '!= nil'?\
> “""

Yes, I think there is a good reason to force an additional newline in this: the 
beginnings of the line are not aligned otherwise or the editor would be 
required to create custom indentation based on the position of the leading "““ 
and whether it is followed by text or not (shudder).

To summarize:

1.
I support Adrian’s idea of requiring that the opening triple quote may not be 
followed by text if and only if the closing triple quote is not preceded by 
text, i.e. only the following two forms are allowed:

a. single line form
"""text"“"

b. multiline form (whitespace allowed before each line, of course)
"“"↵
text↵
""“


2.
Furthermore I would strip the first newline and keep the last newline. As 
Adrian put it quite well: each line between the triple quotes is part of the 
string and ends with a newline (except if ending with a backslash). This is an 
easy mental model and aligns with the most common use cases.

"“"↵
text↵
""“
 would therefore be equal to """text↵"“"

3.
In addition I support Adrian’s idea of stripping trailing whitespace from the 
content (except newlines). To keep trailing whitespace it must be ended with a 
backslash and thereby made visible. That is similar to my idea of always using 
\n for the newlines within a multiline string which has already been 
incorporated into the proposal (thanks for that!).


-Thorsten


> 
> I mean, we certainly could, but I'm not convinced we should. At least, not 
> yet.
> 
> In any case, trailing newline definitely stays. Leading newline, I'm still 
> thinking about.
> 
> As for other things:
> 
> * I see zero reason to fiddle with trailing whitespace. If it's there, it 
> might be significant or it might not be. If we strip it by default and we 
> shouldn't, the developer has no way to protect it. Let's trust the developer. 
> (And their tooling—Xcode, I believe Git, and most linters already have 
> trailing whitespace features. We don't need them too.)
> 
> * Somebody asked about `"""`-delimited heredocs. I think it's a pretty 
> syntax, but it's not compatible with single-line use of `"""`, and I 

Re: [swift-evolution] Proposal: Split extensions into implementing methods and adding static functions Was: [swift-evolution-announce] [Review] SE-0164: Remove final support in protocol extensions

2017-04-13 Thread Xiaodi Wu via swift-evolution
The retroactive conformance needs to be exportable. If one cannot vend a
library that conforms standard library types to new protocols, then that is
a non-starter.


On Thu, Apr 13, 2017 at 06:07 Howard Lovatt  wrote:

> @Xiaodi,
>
> You can safely post-hoc add protocols and methods provided that they are
> final, do not override, and are not exported from the module. See version 2
> of the proposal below.
>
> -- Howard.
>
> # Proposal: Split extension usage up into implementing methods and adding
> methods and protocols post-hoc
>
>
> Draft 2 (Added support for post-hoc conformance to a protocol - replaced
> static final extensions with final extensions)
>
>
> ## Introduction
>
>
> Currently extension methods are confusing because they have different
> dispatch rules for the same calling syntax. EG:
>
>
> public protocol P {
>
> func mP() -> String
>
>  }
>
> extension P {
>
> func mP() -> String { return "P.mP" }
>
> func mE() -> String { return "P.mE" }
>
> }
>
> struct S: P {
>
> func mP() -> String { return "S.mP" }
>
> func mE() -> String { return "S.mE" }
>
> }
>
> let s = S()
>
> s.mP() // S.mP as expected
>
> s.mE() // S.mE as expected
>
> let p: P = s // Note: s now typed as P
>
> p.mP() // S.mP as expected
>
> p.mE() // P.mE unexpected!
>
>
> Extension methods can also cause compatibility problems between modules,
> consider:
>
>
> In Module A
>
> extension Int: P {
>
> func m() -> String { print("A.m") }
>
> }
>
>
> In Module B
>
> extension Int: P {
>
> func m() -> String { print("B.m") }
>
> }
>
>
> In Module C
>
> import A
>
> import B // Should this be an error
>
> let i = 0
>
> i.m() // Should it return A.m or B.m?
>
>
> This proposal cures the above two problems by separating extension methods
> into two seperate use cases: implementations for methods and adding methods
> and protocols post-hoc.
>
>
> ## Implementing methods
>
>
> If the extension is in the same file as the protocol/struct/class
> declaration then it implements the methods and is dispatched using a
> Vtable. EG:
>
>
> File P.swift
>
> protocol/struct/class P {
>
> // func m() not declared in type since it is added by the
> extension, under this proposal it is an error to include a declaration in a
> type *and* in an extension
>
> }
>
> extension P {
>
> func m() { print("P.m") } // m is added to the
> protocol/struct/class declaration
>
> }
>
>
> Same or other file
>
> struct S: P {
>
> override func m() { print("S.m") } // Note override required
> because m already has an implementation from the extension
>
> }
>
> let p: P = S() // Note typed as P
>
> p.m() // Now prints S.m as expected
>
>
> Extensions in the same file as the declaration can have any access, can be
> final, and can have where clauses and provide inheritable implementations.
>
>
> In a protocol at present there is a difference in behaviour between a
> protocol that declares a method that is then implemented in an extension
> and a protocol that just has the method implemented in an extension and no
> declaration. This situation only applies to protocols, for structs and
> classes you cannot declare in type and implement in extensions. The
> proposal unifies the behaviour of protocol/struct/class with extensions and
> prevents the error of a minor typo between the protocol and extension
> adding two methods instead of generating an error.
>
>
> The implementation needed to achieve this is that a value instance typed
> as a protocol is copied onto the heap, a pointer to its Vtable added, and
> it is passed as a pointer. IE it becomes a class instance. No change needed
> for a class instance typed as a protocol.
>
>
> ## Post-hoc adding protocols and methods
>
>
> A new type of extension is proposed, a "final extension", which can be
> either in or outside the file in which the protocol/struct/class
> declaration is in. EG:
>
>
> protocol P2 {
>
> func m2P()
>
> }
>
> final extension S: P2 { // Note extension marked final
>
> func m2P() { print("SP2.m2P") } // Implicitly final, completely
> implements P2
>
> func m2E() { print("SP2.m2E") } // Implicitly final, not an
> existing method
>
> }
>
>
> Which are called as any other method would be called:
>
>
> let s = S()
>
> s.m2P() // Prints SP2.m2P
>
> s.m2E() // Prints SP2.m2E
>
>
> A method added by a final extension is implicitly final, as the name would
> suggest, and cannot be overridden.
>
>
> If the final extension:
>
>
>   1. Adds a method, e.g. m2E, that method cannot already exist. IE a final
> extension cannot override an existing method or implement a protocol
> declared method that lacks an implementation unless it also post-hoc adds
> the protocol.
>
>
>   2. Adds a protocol then it must implement all the methods in that
> 

Re: [swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread David Sweeris via swift-evolution

> On Apr 13, 2017, at 3:56 AM, Andrew Hart via swift-evolution 
>  wrote:
> 
> Recently I’ve been considering the lack of safety around array indexes. Swift 
> is designed with safety in mind, so this example would not compile:
> 
> var myString: String? = “hello”
> myString.append(“ world!”)
> 
> The string is optional, not guaranteed to exist, so the last line requires a 
> “!” to force-unwrap it.
> 
> 
> 
> public func tableView(_ tableView: UITableView, numberOfRowsInSection 
> section: Int) -> Int {
> let section = self.sections[section]
> 
> return section.items.count
> }
> 
> In this example, we could provide a section number that goes beyond the 
> bounds of the self.sections array, without any warning.
> 
> My suggestion is perhaps arrays should by default return an optional when 
> given an index, and of course they’d support forced-unwrapping too. So you 
> could then do this:
> 
> let section = self.sections[section]
> if section == nil {
> return 0
> } else {
> return section!.items.count
> }
> 
> Or you could do this:
> 
> let section = self.sections[section]!
> 
> return section.items.count
> 
> Of course this would be less convenient in a lot of cases, but this is the 1 
> place where apps seem to encounter a crash, crashing for the same reason 
> that’s especially avoided across most of the rest of Swift.

My understanding is that we need the current behavior to meet performance 
goals. We’ve discussed adding a “safe” subscript before, but the discussion 
usually fizzles out when no clear winner for the argument label emerges.

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


Re: [swift-evolution] [pitch] One-sided Ranges

2017-04-13 Thread Haravikk via swift-evolution
I like the principle in general, but I have some concerns about the range 
syntax. Firstly my concern is that allowing either end of the range to be 
omitted feels like a possible bug to me, so I'm not sure if we should encourage 
that?

I'm wondering if a slightly better alternative might to be to retain the 
operators as binary but to pass Void, like so:

let rangeFrom = 5...()
let rangeTo = ()...5

And so-on. It's not quite as pretty, but makes it clear that no mistake was 
made, and allows the operators to be defined normally taking two arguments of 
Comparable and Void (and vice versa).

It could be neatened up if we could allow a lone underscore as Void, like so:

let rangeFrom = 5..._
let rangeTo = _...5

This is a bit neater looking, and should be consistent with how underscore is 
used elsewhere? I'm not sure if it might conflict though, but I don't think so.

Just I thought, but I dislike the idea that by forgetting a value on a range, 
or making some other typo, I could accidentally define an open ended range and 
change the behaviour of something that accepts both open and closed ranges, I 
think requiring something that explicitly indicates an open range is a bit 
better.

> On 12 Apr 2017, at 17:40, Ben Cohen via swift-evolution 
>  wrote:
> 
> Hi Swift community,
> 
> Another proposal pitch. These operators were mentioned briefly in the String 
> manifesto as prefixing/suffixing is very common with strings.
> 
> Online copy here: 
> https://github.com/airspeedswift/swift-evolution/blob/71b819d30676c44234bac1aa61fc5c39bcf3/proposals/-OneSidedRanges.md
>  
> 
> One-sided Ranges
> 
> Proposal: SE- 
> 
> Authors: Ben Cohen , Dave Abrahams 
> , Brent Royal-Gordon 
> 
> Review Manager: TBD
> Status: Awaiting review
> Introduction
> 
> This proposal introduces the concept of a “one-sided” range, created via 
> prefix/postfix versions of the existing range operators.
> 
> It also introduces a new protocol, RangeExpression, to simplify the creation 
> of methods that take different kinds of ranges.
> 
> Motivation
> 
> It is common, given an index into a collection, to want a slice up to or from 
> that index versus the start/end.
> 
> For example (assuming String is once more a Collection):
> 
> let s = "Hello, World!"
> let i = s.index(where: ",")
> let greeting = s[s.startIndex.. When performing lots of slicing like this, the verbosity of repeating 
> s.startIndex is tiresome to write and harmful to readability.
> 
> Swift 3’s solution to this is a family of methods:
> 
> let greeting = s.prefix(upTo: i)
> let withComma = s.prefix(through: i)
> let location = s.suffix(from: i)
> The two very different-looking ways to perform a similar task is jarring. And 
> as methods, the result cannot be used as an l-value.
> 
> A variant of the one-sided slicing syntax found in Python (i.e. s[i:]) is 
> proposed to resolve this.
> 
> Proposed solution
> 
> Introduce a one-sided range syntax, where the “missing” side is inferred to 
> be the start/end:
> 
> // half-open right-handed range
> let greeting = s[.. // closed right-handed range
> let withComma = s[...i]
> // left-handed range (no need for half-open variant)
> let location = s[i...]
> Additionally, when the index is a countable type, i... should form a Sequence 
> that counts up from i indefinitely. This is useful in forming variants of 
> Sequence.enumerated() when you either want them non-zero-based i.e. zip(1..., 
> greeting), or want to flip the order i.e. zip(greeting, 0...).
> 
> This syntax would supercede the existing prefix and suffix operations that 
> take indices, which will be deprecated in a later release. Note that the 
> versions that take distances are not covered by this proposal, and would 
> remain.
> 
> This will require the introduction of new range types (e.g. 
> PartialRangeThrough). There are already multiple range types (e.g. 
> ClosedRange, CountableHalfOpenRange), which require overloads to allow them 
> to be used whereever a Range can be.
> 
> To unify these different range types, a new protocol, RangeExpression will be 
> created and all ranges conformed to it. Existing overloads taking concrete 
> types other than Range can then be replaced with a single generic method that 
> takes a RangeExpression, converts it to a Range, and then forward the method 
> on.
> 
> A generic version of ~= will also be implemented for all range expressions:
> 
> switch i {
> case 9001...: print("It’s over NINE THOUSAAAND")
> default: print("There's no way that can be right!")
> }
> The existing concrete overloads that take ranges other than Range will be 
> deprecated in favor of generic ones that take a RangeExpression.
> 
> Detailed 

Re: [swift-evolution] Proposal: Split extensions into implementing methods and adding static functions Was: [swift-evolution-announce] [Review] SE-0164: Remove final support in protocol extensions

2017-04-13 Thread Howard Lovatt via swift-evolution
@Xiaodi,

You can safely post-hoc add protocols and methods provided that they are final, 
do not override, and are not exported from the module. See version 2 of the 
proposal below. 

-- Howard.

# Proposal: Split extension usage up into implementing methods and adding 
methods and protocols post-hoc

Draft 2 (Added support for post-hoc conformance to a protocol - replaced static 
final extensions with final extensions)

## Introduction

Currently extension methods are confusing because they have different dispatch 
rules for the same calling syntax. EG:

public protocol P {
func mP() -> String
 }
extension P {
func mP() -> String { return "P.mP" }
func mE() -> String { return "P.mE" }
}
struct S: P {
func mP() -> String { return "S.mP" }
func mE() -> String { return "S.mE" }
}
let s = S()
s.mP() // S.mP as expected
s.mE() // S.mE as expected
let p: P = s // Note: s now typed as P
p.mP() // S.mP as expected
p.mE() // P.mE unexpected!

Extension methods can also cause compatibility problems between modules, 
consider:

In Module A
extension Int: P {
func m() -> String { print("A.m") }
}

In Module B
extension Int: P {
func m() -> String { print("B.m") }
}

In Module C
import A
import B // Should this be an error
let i = 0
i.m() // Should it return A.m or B.m?

This proposal cures the above two problems by separating extension methods into 
two seperate use cases: implementations for methods and adding methods and 
protocols post-hoc. 

## Implementing methods

If the extension is in the same file as the protocol/struct/class declaration 
then it implements the methods and is dispatched using a Vtable. EG:

File P.swift
protocol/struct/class P {
// func m() not declared in type since it is added by the extension, 
under this proposal it is an error to include a declaration in a type *and* in 
an extension
}
extension P {
func m() { print("P.m") } // m is added to the protocol/struct/class 
declaration
}

Same or other file
struct S: P {
override func m() { print("S.m") } // Note override required because m 
already has an implementation from the extension
}
let p: P = S() // Note typed as P
p.m() // Now prints S.m as expected 

Extensions in the same file as the declaration can have any access, can be 
final, and can have where clauses and provide inheritable implementations. 

In a protocol at present there is a difference in behaviour between a protocol 
that declares a method that is then implemented in an extension and a protocol 
that just has the method implemented in an extension and no declaration. This 
situation only applies to protocols, for structs and classes you cannot declare 
in type and implement in extensions. The proposal unifies the behaviour of 
protocol/struct/class with extensions and prevents the error of a minor typo 
between the protocol and extension adding two methods instead of generating an 
error.

The implementation needed to achieve this is that a value instance typed as a 
protocol is copied onto the heap, a pointer to its Vtable added, and it is 
passed as a pointer. IE it becomes a class instance. No change needed for a 
class instance typed as a protocol. 

## Post-hoc adding protocols and methods

A new type of extension is proposed, a "final extension", which can be either 
in or outside the file in which the protocol/struct/class declaration is in. EG:

protocol P2 {
func m2P()
}
final extension S: P2 { // Note extension marked final
func m2P() { print("SP2.m2P") } // Implicitly final, completely 
implements P2
func m2E() { print("SP2.m2E") } // Implicitly final, not an existing 
method
}

Which are called as any other method would be called:

let s = S()
s.m2P() // Prints SP2.m2P
s.m2E() // Prints SP2.m2E

A method added by a final extension is implicitly final, as the name would 
suggest, and cannot be overridden. 

If the final extension:

  1. Adds a method, e.g. m2E, that method cannot already exist. IE a final 
extension cannot override an existing method or implement a protocol declared 
method that lacks an implementation unless it also post-hoc adds the protocol.

  2. Adds a protocol then it must implement all the methods in that protocol 
that are not currently implemented.

  3. Is outside of the file in which the protocol/struct/class declaration is 
in then the extension and the methods can only have fileprivate or internal 
access. This prevents post-hoc extensions from numerous modules clashing, since 
they are not exported outside of the module. 

## Possible future work (not part of this proposal)

This proposal will naturally allow bodies to be added to protocols directly 
rather than via an extension, since under the proposal the extension adds the 
declaration to the type so it is a small step to allow the 

[swift-evolution] [Pitch] Adding safety to arrays

2017-04-13 Thread Andrew Hart via swift-evolution
Recently I’ve been considering the lack of safety around array indexes.
Swift is designed with safety in mind, so this example would not compile:

var myString: String? = “hello”
myString.append(“ world!”)

The string is optional, not guaranteed to exist, so the last line requires
a “!” to force-unwrap it.



public func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
let section = self.sections[section]

return section.items.count
}

In this example, we could provide a section number that goes beyond the
bounds of the self.sections array, without any warning.

My suggestion is perhaps arrays should by default return an optional when
given an index, and of course they’d support forced-unwrapping too. So you
could then do this:

let section = self.sections[section]
if section == nil {
return 0
} else {
return section!.items.count
}

Or you could do this:

let section = self.sections[section]!

return section.items.count

Of course this would be less convenient in a lot of cases, but this is the
1 place where apps seem to encounter a crash, crashing for the same reason
that’s especially avoided across most of the rest of Swift.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] struct finalization constraint for protocols

2017-04-13 Thread Adrian Zubarev via swift-evolution
Honestly I read your post twice and I still having issues to understand what 
exactly you’re proposing.

Now about final on protocols. IMO this is a bad choice, because I would think 
that you cannot conform to that protocol, not could you refine it with another 
protocol, because it’s final after all.

The whole post seemed to me like an *existential of structs* with a special 
interface, am I wrong here?

I myself would want to see more constraints for protocols like this:

protocol P1 : AnyStruct { … } // for structs only
protocol P2 : AnyEnum { … }   // for enums only
protocol P3 : AnyValue { … }  // for any extensible value type

protocol p4 : ValueSemantics { … } // Force value semantics (can be a class if 
not constrained otherwise)

// Soon we'll have this (SE-0156: 
https://github.com/apple/swift-evolution/blob/master/proposals/0156-subclass-existentials.md)
protocol P5 : AnyObject { … }

// instead of
protocol P5 : class { … }


-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 11:25:49, Andrey Volodin via swift-evolution 
(swift-evolution@swift.org) schrieb:

Hello everyone!

First of all, I know swift goes into a bit different direction for super type 
safety, but the problem that is going to describe is kind of common to anybody 
who use general purpose library (that are not bound to any big UI/non-UI 
framework).

I’m a game-engine and deep learning developer and I use Swift on the daily 
basis. The thing I think that Swift really misses is struct protocols. Here is 
the basic example. 

Problem: 
Imagine you do a game with some sort of game engine. That game engine is based 
on some math lib and you store all vector data (i.e. positions etc) in the 
something like Point2D from that lib. And then you decided that you need to 
draw a complex polygons in your game. So you search for a triangulation lib. 
And you find it, but it uses its own format to describe points, say 
Triangulation.Point. The thing is that you have a huge buffer of points to 
triangulate, but you need to map every single one of them to that new format of 
that lib and than convert it back. 

Proposal:
Wouldn’t it be nice if we could invent a way to globalize types like that? 

Imagine you declare something like this in your imaginary triangulation library:

final public protocol Vector2D { // or the syntax could be `Vector2D: struct`
    var x: Double { get set }
    var y: Double { get set }
}

And base the algorithm on this one. So you tell the compiler that we will 
operate on the structs with a known and final layout. Then in your application 
you only need to do:

public extension Point2D: Vector2D {}

Types that will conform to such protocols will have some very strict 
constraints. For example they will have to have the same memory layout (i.e. no 
protocol variables), stored properties in extensions (that are coming soon) 
will be also forbidden for such types. The goal is to decrease the need of 
converting data when you don’t really have to. Those types will have to have 
the same properties, in the same order, all of them must be stored ones.

For example we have a bunch of C libs like OpenCV or dlib and every one of them 
has its own image format. Every single one has own its pixel struct and you 
always need to convert between them. 

I personally think that having something like «type globalization» can improve 
language ecosystem overall and make things more cross-platform. You can think 
of it as a typealiasing but without knowing a type you are aliasing to. The 
compiler will just merge all those types into one during compilation.

Once again: I know this is kind of arguable thing, I just wanted to know your 
opinion on that.

Thanks for your attention,
Andrey Volodin
___
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] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Assuming the multi-line string literal to behave like I summarized it in my 
last post and that the for loop runs two times, we’d have to alter your example 
a little, which will then feel natural for concatenation.

I use tabs for ident.

// Notice the blank line at the end, which does  
// not inject a new line after itself
var xml = """


 
"""
 
for (id, author, title, genre, price) in bookTuples {
 
// Same here, a blank line at the end which does not
// inject a new line after itself. It's natural for  
// concatenation.
xml += """

\(author)
\(title)
\(genre)
\(price)

 
"""
}

xml += """

"""
You could also write \n or \n\ instead of an explicit new line, but I think 
it’s natural enough that way, because now the reader of the code sees that the 
next concatenation will happen on the blank line (equivalent to "" + "string 
from the next iteration").

The result:




A
B
D
42


A
C
D
42

   


-- 
Adrian Zubarev
Sent with Airmail

Am 13. April 2017 um 11:03:33, Brent Royal-Gordon (br...@architechies.com) 
schrieb:

var xml = """
    
    
    """
for (id, author, title, genre, price) in bookTuples {
    xml += """
            
                \(author)
                \(title)
                \(genre)
                \(price)
            
        """
}
xml += """
    
    """
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Adrian Zubarev via swift-evolution
Now that I had some sleep I actually revise my opinion about the last line. I 
took a few hours to sum my thoughts together in a gist, here is a formatted 
version of it: 
https://gist.github.com/DevAndArtist/dae76d4e3d4e49b1fab22ef7e86a87a9

Simple ‘multi-line string literal’ model

Core features:

Omitting of (most) backslashes for ".
Altering the string with implicit new line injection at the end of the line.
Consequences of #1:

To omit escaping the quote character, the delimiter characters for the 
multi-line string literal will be tripled quotes """, also similar to other 
programming languages.

When a standard string literal contains at least 5 quotes, then the usage of a 
multi-line string literal will be shorter.

""// With escapes
""  // With tripled literals
Consequences of #2:

To fully support this feature, we need to compromise the design for simplicity 
and intuitivity.

This feature needs precision for leading and trailing spaces.
Alternatively one would need a way to disable new line injection to also 
support code formatting.
Two ways of writing a multi-line string literal:

Single line version """abc""" is trivial and already was shown above.

The multi-line version comes with a few compromises for simplicity of rules:

"""   // DS (delimiter start)
foo   // s0
foo   // s1
foo   // s2
"""   // DE (delimiter end)
The string content is always written between the lines DS and DE (delimiter 
lines).

To not to go the continuation quotes path, the left (or leading) precision is 
handled by the closing delimiter (1. compromise). The closing delimiter is also 
responsible for the indent algorithm, which will calculate the stripping prefix 
in line DE and apply stripping to lines s0 to sn.

Right (or trailing) precision of each line from s0 to sn (notice n equals 2 in 
the example above) is handled by a backslash character (2. compromise).

The right precision comes at a price of losing the implicit new line injection, 
however this was also a requested feature (3. compromise). That means that the 
backslash serves two jobs simultaneously.

New line injection happens only on lines s0 to s(n - 1) (4. and last compromise 
of the design). The last line sn (or s2 above) does not inject a new line into 
the final string. This implies that in this line a backslash character handles 
only right precision, or one could say it’s reduced to one functionality.

Important:

Because whitespace is important to these examples, it is explicitly indicated: 
· is a space, ⇥ is a tab, and ↵ is a newline.

Leading/trailing precision and indent (1. and 2. compromise):

// Nothing to strip in this example (no ident).
let str_1 = """↵  
foo↵
"""

// No right precision (no backslash) -> whitespaces will be stripped.
let str_2 = """↵  
foo··↵
"""

// Same as `str_2`
let str_3 = """↵  
foo↵
"""

// Line `DE` of the closing delimiter calculates the indent prefix  
// `··` and strips it from `s0` (left precision).
let str_4 = """↵  
··foo↵
··"""

// Line `DE` of the closing delimiter calculates the indent prefix  
// `` and strips it from `s0` (left precision).
// No right precision (no backslash) -> whitespaces will be stripped.
let str_5 = """↵  
foo··↵
"""

// Line `DE` of the closing delimiter calculates the indent prefix  
// `⇥ ⇥ ` and strips it from `s0` (left precision).
// Right precision is applied (backslash). In this case the literal
// contains only a single line of content, which happens to be   
// also the last line before `DE` -> backslash only serves precision.
let str_6 = """↵  
⇥ ⇥ foo\↵
⇥ ⇥ """

// Line `DE` of the closing delimiter calculates the indent prefix  
// `·⇥ ·⇥ ` and strips it from `s0` (left precision).
// No right precision (no backslash) -> whitespaces will be stripped.
let str_7 = """↵  
·⇥ ·⇥ foo··↵
·⇥ ·⇥ """

let string_1 = "foo"

str_1 == string_1   // => true
str_2 == string_1   // => true
str_3 == string_1   // => true
str_4 == string_1   // => true
str_5 == string_1   // => true
str_6 == string_1   // => true
str_7 == string_1   // => true
A false multi-line string literal, which compiles but emits a warning and 
proves a fix-it:

let str_8 = """↵  
··foo↵
"""

str_8 == string_1   // => true
warning: missing indentation in multi-line string literal
  ··foo!
^  
  Fix-it: Insert "··"
The stripping algorithm calculates the prefix indent from the closing delimiter 
line DE and tries to strip it in lines s0 to sn if possible, otherwise each 
line, which could not be handled correctly will emit an individual warning and 
a fix-it.

The stripping algorithm removes every whitespace on the end of each line from 
s0 to sn iff there is no right precision, annotated through a backslash like 
··foo··\↵. This behavior is essential and aligns well with the precision 
behavior of a standard string literal " ", otherwise a multi-line string 
literal like

"""
foo
"""
can contain 3 characters or 10 characters or even 1000 characters, but the 
developer 

[swift-evolution] struct finalization constraint for protocols

2017-04-13 Thread Andrey Volodin via swift-evolution
Hello everyone!

First of all, I know swift goes into a bit different direction for super type 
safety, but the problem that is going to describe is kind of common to anybody 
who use general purpose library (that are not bound to any big UI/non-UI 
framework).

I’m a game-engine and deep learning developer and I use Swift on the daily 
basis. The thing I think that Swift really misses is struct protocols. Here is 
the basic example. 

Problem: 
Imagine you do a game with some sort of game engine. That game engine is based 
on some math lib and you store all vector data (i.e. positions etc) in the 
something like Point2D from that lib. And then you decided that you need to 
draw a complex polygons in your game. So you search for a triangulation lib. 
And you find it, but it uses its own format to describe points, say 
Triangulation.Point. The thing is that you have a huge buffer of points to 
triangulate, but you need to map every single one of them to that new format of 
that lib and than convert it back. 

Proposal:
Wouldn’t it be nice if we could invent a way to globalize types like that? 

Imagine you declare something like this in your imaginary triangulation library:

final public protocol Vector2D { // or the syntax could be `Vector2D: struct`
var x: Double { get set }
var y: Double { get set }
}

And base the algorithm on this one. So you tell the compiler that we will 
operate on the structs with a known and final layout. Then in your application 
you only need to do:

public extension Point2D: Vector2D {}

Types that will conform to such protocols will have some very strict 
constraints. For example they will have to have the same memory layout (i.e. no 
protocol variables), stored properties in extensions (that are coming soon) 
will be also forbidden for such types. The goal is to decrease the need of 
converting data when you don’t really have to. Those types will have to have 
the same properties, in the same order, all of them must be stored ones.

For example we have a bunch of C libs like OpenCV or dlib and every one of them 
has its own image format. Every single one has own its pixel struct and you 
always need to convert between them. 

I personally think that having something like «type globalization» can improve 
language ecosystem overall and make things more cross-platform. You can think 
of it as a typealiasing but without knowing a type you are aliasing to. The 
compiler will just merge all those types into one during compilation.

Once again: I know this is kind of arguable thing, I just wanted to know your 
opinion on that.

Thanks for your attention,
Andrey Volodin___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0168: Multi-Line String Literals

2017-04-13 Thread Brent Royal-Gordon via swift-evolution
> On Apr 12, 2017, at 5:39 PM, Xiaodi Wu  wrote:
> 
> On Wed, Apr 12, 2017 at 5:20 PM, Brent Royal-Gordon  > wrote:
> Wow, maybe I shouldn't have slept.
> 
> Okay, let's deal with trailing newline first. I'm *very* confident that 
> trailing newlines should be kept by default. This opinion comes from lots of 
> practical experience with multiline string features in other languages. In 
> practice, if you're generating files in a line-oriented way, you're usually 
> generating them a line at a time. It's pretty rare that you want to generate 
> half a line and then add more to it in another statement; it's more likely 
> you'll interpolate the data. I'm not saying it doesn't happen, of course, but 
> it happens a lot less often than you would think just sitting by the fire, 
> drinking whiskey and musing over strings.
> 
> I know that, if you're pushing for this feature, it's not satisfying to have 
> the answer be "trust me, it's not what you want". But trust me, it's not what 
> you want.
> 
> This is not a very good argument. If you are generating files in a 
> line-oriented way, it is the function _emitting_ the string that handles the 
> line-orientedness, not the string itself. That is the example set by 
> `print()`:
> 
> ```
> print("Hello, world!") // Emits "Hello, world!\n"
> ```

You say "this is the example set by `print`", but I don't think anything else 
actually *follows* that example. No other I/O operation in Swift behaves this 
way. The underlying `TextOutputStream.write(_:)` doesn't; the I/O in Foundation 
doesn't; file descriptor I/O doesn't. Concatenation certainly doesn't; nor does 
anything else you might do to assemble several multiline string literals into a 
whole. So I think `print()` is the exception here, not the rule.

In my opinion, modulo the "newline after leading delimiter" question, if code 
like this example:

var xml = """


"""

for (id, author, title, genre, price) in bookTuples {
xml += """

\(author)
\(title)
\(genre)
\(price)

"""
}

xml += """

"""

Doesn't assemble the kind of string that it's blatantly obvious the user is 
trying to assemble, I think the syntax has failed.

`print()` is the outlier. It's an important enough outlier that we should 
probably help the user notice when they're about to get it wrong, but an 
outlier it is.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0169: Improve Interaction Between private Declarations and Extensions

2017-04-13 Thread Goffredo Marocchi via swift-evolution
+1

Sent from my iPhone

> On 13 Apr 2017, at 08:15, Tino Heth via swift-evolution 
>  wrote:
> 
>> No change
>> Benefit: No change to the language.
>> Drawback: Must use “fileprivate” to build up a type through extensions.
>> 
>> SE–0159
>> Benefit: Simplifies the access control model.
>> Drawback: Cannot protect invariants within a file.
>> 
>> SE–0169
>> Benefit: Cross-type sharing is clearly marked.
>> Drawback: Must use a helper type to protect invariants within a file.
>> 
>> Rename
>> Benefit: No change to semantics.
>> Drawback: Two separate keywords are changed.
> 
> 
> As the dedicated thread was highjacked ;-), imho it's just fair to add 
> another option here...
> 
> Nested extensions
> Benefit: Expressive power, no breaking change (and more…)
> Drawback: More indentation
> 
> The table is quite boring:
> Nested Extensions
> Simple file   private
> Extensionsprivate
> Sharing   private
> Helper visibleprivate
> Helper hidden private
> Invariantsprivate
> Multi-typeprivate
> Multi-type + ext  private
> 
> I'm not sure about the colour, but if I wasn't to lazy to edit raw HTML, imho 
> there would a lot of green ;-)
> ___
> 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-evolution-announce] [Review] SE-0169: Improve Interaction Between private Declarations and Extensions

2017-04-13 Thread Tino Heth via swift-evolution
> No change
> Benefit: No change to the language.
> Drawback: Must use “fileprivate” to build up a type through extensions.
> 
> SE–0159
> Benefit: Simplifies the access control model.
> Drawback: Cannot protect invariants within a file.
> 
> SE–0169
> Benefit: Cross-type sharing is clearly marked.
> Drawback: Must use a helper type to protect invariants within a file.
> 
> Rename
> Benefit: No change to semantics.
> Drawback: Two separate keywords are changed.


As the dedicated thread was highjacked ;-), imho it's just fair to add another 
option here...

Nested extensions
Benefit: Expressive power, no breaking change (and more…)
Drawback: More indentation

The table is quite boring:
Nested Extensions
Simple file private
Extensions  private
Sharing private
Helper visible  private
Helper hidden   private
Invariants  private
Multi-type  private
Multi-type + extprivate

I'm not sure about the colour, but if I wasn't to lazy to edit raw HTML, imho 
there would a lot of green ;-)___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Unify the way properties and methods work to make key-value coding more natural

2017-04-13 Thread Tino Heth via swift-evolution

> While the \ syntax will only apply to key paths to begin with, we want to 
> look into unifying all unapplied member references under that syntax.

Glad to hear that — I hope the core team will keep the courage to break syntax 
from time to time if the change improves the consistency of Swift.
But like anyone else, I prefer breaking changes to happen rarely, and I think 
other parts of the language should be taken into account as well.

KVC is nice, but I would really like to see some sort of namespace for querying 
and working with "meta-properties":
— function references
— properties
— MemoryLayout
— functions (I'm thinking of stuff like introspection of parameters, and 
something like "apply" as a replacement for tuple splat)
— mirrors
— (most likely, I forgot some other possibilities)

There's no concrete vision for such a concept, but I'll just use ":" for 
illustration...
let appender: (Array, Int) -> Void = Array:methods:append
let someStaticFunction = MyType:classMethods:setGlobalInstance
let sizeProperty = Array:properties:size
let bytesNeeded = Double:memoryLayout.size
if theFunction:signature.parameters = [Int, Int] && 
theFunction:signature.returnType == T {
return theFunction:callWith(myPairOfInt)
}
let parent = Self:superclass
for type in UIViewController:allKnownSubclasses {…

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