Re: [swift-evolution] [Review] SE-0194: Derived Collection of Enum Cases

2018-01-10 Thread Kevin Nattinger via swift-evolution
> [...]
> 
> I don’t agree that the Collection should be Int-indexed. Source-order is not 
> a very strong guarantee IMO, and it wouldn’t be good if people started 
> writing things like "MyEnum.allValues[3]” to reference a specific case.

So how do you propose to use allValues with a table view? That's one of the 
motivating examples, and probably the most common use case. Certainly the most 
common I've seen.

> 
> If you know the specific case you are looking for, just write it directly. If 
> you found an interesting case while iterating allValues, remember its 
> (opaque) index and come back to it later.
> 
> I’m not a fan of Int-indexes in general. It’s practical to allow it for 
> Array, but in general, for generic Collections, I think it implies an awful 
> lot of knowledge about the Collection’s contents.
> 
> - Karl
> ___
> 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-0194: Derived Collection of Enum Cases

2018-01-09 Thread Kevin Nattinger via swift-evolution
> Proposal link:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md
>  
> 
>  
> What is your evaluation of the proposal?
+1 on the general problem, but I have a few comments on the design specifics

- I'd very much prefer automatic synthesis with enums, 
- I strongly feel the compiler should auto-generate the implementation in an 
extension for enums.
- Should we add `ValueCollection.Index == Int` to the associatedtype so it can 
always be indexed as in a table? 
  - At the least, we should ensure the synthesized implementation is 
int-indexed for tables.
- I feel we should allow auto-generation of imported c enums in an extension, 
as just an array of the known cases rather than the magical metadata iterator 
if necessary. 

> Is the problem being addressed significant enough to warrant a change to 
> Swift?
Definitely. It's been a gaping hole in the language since the beginning.

> Does this proposal fit well with the feel and direction of Swift?
Yes

> If you have used other languages or libraries with a similar feature, how do 
> you feel that this proposal compares to those?
I prefer Java's automatic allValues(), but this is better than nothing.

> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?
Followed at least the start of several threads and read the proposal.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE 0192 - Non-Exhaustive Enums

2018-01-03 Thread Kevin Nattinger via swift-evolution
>>> [...]
>>> 2️⃣ If the enum is NOT decorated with @frozen, then I, as an app 
>>> author, have to account for the possibility that the module may update from 
>>> underneath my app, and I have to handle an unknown case. This is simple: 
>>> the compiler should require me to add a “default:” case to my switch 
>>> statement. This warning is produced IFF: the enum is coming from an 
>>> external module, and the enum is not decorated with @frozen.
>> 
>> This does not help people who need to write a switch statement over an enum 
>> vended by a module that ships with the OS keep their code up to date as the 
>> module adds new cases. I find the example of `SKPaymentTransactionState` 
>> provided by Brent Royal-Gordon here: 
>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170904/039512.html
>>  
>> 
>>  to be compelling.  There are rare but legitimate reasons to switch over all 
>> known cases of a non-@frozen enum that ship with the OS.  These use cases 
>> deserve proper language support.  I think Jordan’s solution strikes a good 
>> balance.
> 
> I disagree that more is needed. In the case of the transaction state, it 
> should not be marked as @moana, and so the compiler would force you to add a 
> “default” case to your switch statements. The switch statements would still 
> be exhaustive with all known cases (if you choose to handle all known cases), 
> but you’d still need a default case because there might be new transaction 
> states in the future.

And then you don't get the compiler error/warning when you start compiling 
against the next OS update that changes the enum. That is an absolutely 
unacceptable loss of compile-time checks.

> 
> In those cases, your app could decide what to do, if that’s possible at all. 
> Maybe there’s other transaction information you could introspect to determine 
> if it succeeded or is still pending or whatever, and then your app could 
> respond as you see fit.
> 
> Dave
> ___
> 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 0192 - Non-Exhaustive Enums

2018-01-02 Thread Kevin Nattinger via swift-evolution
[...]

>> in what other circumstances do we insist that the compiler inform the end 
>> user about future additions to the API at compile time?
> 
> This isn’t a request for the compiler to inform the user about future 
> additions to an API.  It is a request to validate the compiler’s knowledge of 
> the current state of an API with the current state of the source code. 
> 
> Well, it's of course impossible to inform the user about future additions, so 
> that's poorly phrased on my part. It's about the compiler informing the end 
> user about *new* additions, part of the *current* state of the API, that have 
> cropped up since the user last revised the code when the API was in a 
> *previous* state (or, indistinguishably, members of which a user is unaware 
> regardless of the temporal sequence of when such members were added). In what 
> other circumstances do we insist that the compiler perform this service?

Enums. That's literally how they work today. You are arguing in favor of 
actively removing compiler-aided correctness.

There's also protocol requirements and, arguably, deprecated methods with a 
proper message ("use foo instead").

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


Re: [swift-evolution] Enums and Source Compatibility

2017-12-21 Thread Kevin Nattinger via swift-evolution

> On Oct 2, 2017, at 2:10 PM, Jordan Rose via swift-evolution 
>  wrote:
> 
> I don't think I have anything to say on this topic that I haven't already 
> said:
> 
> - Switching exhaustively over non-exhaustive enums is uncommon.

[Citation Needed]
As I pointed out in my email in the review thread, there are a significant 
number of enums in Apple's own frameworks that are commonly switched over 
exhaustively.

Additionally, uncommon or not, when this does come up, it's an enormous issue. 
Big enough that "it's uncommon" isn't sufficient justification for ignoring it.

> - It's more important for a library to build without errors when its 
> dependencies change than it is to get an error. (This doesn't apply to 
> warnings, though.)

Not sure I agree with this. In fact I think if anything it's more important for 
libraries than clients. Especially in the case of a new enum value it should 
support but doesn't.

> - Untestable code is dangerous, so having a language feature inherently for 
> untestable code seems bad.

A `default` case in the same situation is just as untestable, as you even point 
out in the proposal. Why do you keep using this as an argument against `future` 
but not `default`?

> 
> None of that negates your points; it just affects the weighting of whether or 
> not 'future' or 'switch!' is worth it. However, I've added a link to your 
> email in the proposal proper so that the Core Team and wider review audience 
> have a chance to decide differently.
> 
> Jordan
> 
> 
>> On Oct 2, 2017, at 08:25, Vladimir.S via swift-evolution 
>> > wrote:
>> 
>> 
>> Sorry to bother, but I still can't understand how the proposed change 
>> *without* a 'future' case in switch will change our life and what would be 
>> our steps to support our code and to not make our code buggy.
>> If I misunderstand something - sorry, please point me on this and I hope 
>> this also help some one like me to understand the subject better.
>> 
>> For example. I use OAuth2 framework, built by Carthage. Did add the 
>> OAuth2.framework to my project.
>> 
>> Currently OAuth2 exports 'public enum OAuth2Error'. I do have a place in my 
>> code where I switch on each case of such error instance to do my best with 
>> error: generate detailed description for user, other additional steps 
>> depending on error.
>> 
>> Will/should author of OAuth2 make OAuth2Error 'exhaustive' ? No.
>> Will new cases be added to that enum in future: Most likely Yes.
>> Do I need to switch on each case in my code? Yes.
>> Can I currently rely on compiler to keep my error processing in sync with 
>> error cases defined in framework? Yes.
>> Can new cases appear in *run-time* of my app: NO, framework in embedded.
>> Will I be able to rely on compiler after the proposed change? No?!
>> What should I do to keep my switch in sync with OAuth2Error cases after each 
>> update of OAuth2 library(framework)? Manually check if new cases are added?! 
>> Configure lint/other tools to help me with this?!
>> 
>> What I, as a developer, as a consumer of framework, need - is a way to 
>> exhaustively switch on *some* external non-exhaustive enums *at the moment 
>> of compilation*. And we can accomplish this only(AFAICT) with 'future' case 
>> in 'switch'.
>> In case we'll have 'future' case my life will not be *worse* for this 
>> project : I'll add it to my switch and still can receive help from compiler 
>> to keep switch exhaustive.
>> 
>> I don't support the opinion that we can't introduce 'future' case because of 
>> we can't test it:
>> 
>> 1. Not being able to keep my switch exhaustive when I need this, and so not 
>> being able to provide users of my app with best experience - IMO is worse.
>> 2. In my particular example, 'future' case will be *never* called, if I 
>> understand correctly.
>> 3. If switch on non-exhaustive enum is exhaustive by fact, we can't test the 
>> 'default' branch also. So, 'future' is in same position here with 'default'
>> 4. I believe if we'll decide we need 'future' case - we can suggest a way to 
>> call code in that case during the test process.
>> 
>> Seems like for embedded frameworks we should apply the same rules(regarding 
>> enums) as for sources, as we compile the app with concrete binary of 
>> framework and there just can't be new cases in enums. No?
>> 
>> Thank you for your time.
>> Vladimir.
>> 
>> On 01.10.2017 3:00, Slava Pestov via swift-evolution wrote:
 On Sep 30, 2017, at 4:46 PM, Karl Wagner via swift-evolution 
  
 >> 
 wrote:
 
 I don’t see how it’s impractical. Quite a lot about how the library should 
 be optimally compiled and used depends on what you plan to do with it. If 
 it’s going to be installed somewhere private and you can guarantee clients 
 

Re: [swift-evolution] The Non-Exhaustive Enums proposal kills one of Swift's top features - change proposal

2017-12-21 Thread Kevin Nattinger via swift-evolution
>> [...]
> 
> Hi, Nacho. This is discussed in the proposal as "'future' cases" under 
> "Alternatives considered". The main blocker was that such a case becomes 
> untestable (see also "Testing invalid cases"). That didn't seem like an 
> acceptable state of affairs to me or to the people I had originally discussed 
> the proposal with, but maybe the community feels differently?

As you state in the proposal, using `default` instead is exactly as untestable, 
in exactly the same way. Using that as an argument against future but not 
default is disingenuous. And default additionally introduces the enormous issue 
of killing compile-time safety, while future does not..

> 
> I would love if someone could think of something I haven't yet; by no means 
> do I think I'm the only one who can have ideas in this space.
> 
> Jordan
> ___
> 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 0192 - Non-Exhaustive Enums

2017-12-21 Thread Kevin Nattinger via swift-evolution
> On Dec 19, 2017, at 2:58 PM, Ted Kremenek via swift-evolution 
>  wrote:
> 
> The review of "SE 0192 - Non-Exhaustive Enums" begins now and runs through 
> January 3, 2018.
> 
> The proposal is available here:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md
>  
> 
> What is your evaluation of the proposal?
> 
I was going to say -100 without future, +1 with, but other arguments on this 
thread have put me on the fence to mildly against, so -100 without future, -ε 
with.


In the proposal, there is the following text:
> The consequences of losing exhaustiveness checking for non-exhaustive enums 
> are discussed in the "Alternatives considered" section at the end of this 
> proposal.
> 
> A number of pre-reviewers have been concerned about the loss of 
> exhaustiveness checking and the subsequent difficulty in updating to a new 
> version of a dependency. In the original swift-evolution thread, Vladimir S. 
> describes the concerning scenario 
> 
>  in detail.
I find it deeply disturbing that this scenario is acknowledged as "concerning" 
and yet ignored without justification in the proposal proper, and in the 
"alternatives" dismissed solely based on a baseless assumption—that the 
situation will be "uncommon." Even if it were an uncommon case, the negative 
impact is still dire enough and without a good workaround that I'd argue 
strongly that the concern be addressed properly.

The justification put forward to reject a `future` case is that "The 
expectation is that switches over non-exhaustive enums are uncommon." However, 
there is no evidence to support that assertion, and there are a huge number of 
enums in even just Apple's frameworks that people reasonably can, and in some 
cases really should, switch over. Go through any of the iOS frameworks and find 
authorization enums and delegates with enums in a callback, and you're likely 
to find some that it makes sense for a client to switch over. Just a few off 
the top of my head that I have personally switched on:

CoreBluetooth
- CBManagerState
- CBPeripheralManagerAuthorizationStatus
- CBPeripheralState
CoreLocation
- CLAuthorizationStatus
- CLActivityType
CoreData
- NSFetchedResultsChangeType
MessageUI
- MessageComposeResult
UIKit
- UITableViewCellEditingStyle

Every framework that requires user permission has its own authorization enum, 
many have an additional state enum, and for most delegate callbacks with an 
enum argument it's often a good idea to switch over the cases.

As a real-life example above and beyond the one referenced above, In the fairly 
small codebase I'm working in at the moment, I count a bit over 12klocs, 80-ish 
switches, and 6 switches that would need a `future` case (non-exhaustive, from 
Apple frameworks). That's about one per 2klocs, It probably wouldn't scale 
linearly in larger projects, but just their prevalence in the apple frameworks 
as I pointed out above would suggest it does grow significantly.

The extra onus on project authors required by not including a future case for 
those cases would make upgrading libraries and iOS versions incredibly 
difficult and error-prone. To ensure correctness, you would have to go over 
every single switch in your app, figure out the type it's switching on, and if 
the type is external and nonexhaustive, check that there are no new cases. Even 
if this is "not expected to be the common case," omitting the `future` means 
you have to either keep track of where all your relevant switch statements are 
and check them on every upgrade, go through and evaluate every switch statement 
to figure out whether you need to check for extra cases, or go through the API 
diff, find any added enum cases, and find every switch in your codebase that 
switches on them. All three options are dangerously error-prone and 
unacceptable.

In summary, failing to include a future case but requiring default instead 
would place an unacceptable burden on every nontrivial project every time a 
library is upgraded and (and I don't say this lightly) would almost certainly 
be the biggest mistake the Swift community has ever made.

There is an existing implementation along with the PR, so has anyone tried this 
change a project of significant size that uses a variety of Apple frameworks? 
How many `default`s did you have to put in that should be `future`, and how 
would you feel about having to find all those places again and any more that 
may be put in in a year or two *without* compiler checking?
> Is the problem being addressed significant enough to warrant a change to 
> Swift?
> 
The problem needs to be addressed, certainly.
> Does this proposal fit well with the feel and direction of Swift?
> 
With future, sure. Without, absolutely not. As demonstrated 

Re: [swift-evolution] Evaluating the case of an enum with associated values as a bool

2017-12-20 Thread Kevin Nattinger via swift-evolution
I agree this would be useful. At the moment I have to hack around it with 
things like `var isFoo: Bool { if case .foo = self …`* with cases I commonly 
need, but this is definitely a feature that has come up before and I support. 
It is potentially related to getting the values through an accessor, which has 
also come up several times.

Sidenote, your `switch` example is actually trivial with existing syntax:

switch enumeration {
case .a(.c(let param)): // or just .a(.c) if you don't need the value
print(param)
default:
break
}

I use this from time to time switching over, e.g., optional enums.

*: ugliest syntax ever, and it can't even be used as a standalone expression.


> On Dec 20, 2017, at 8:44 AM, Ethan Diamond via swift-evolution 
>  wrote:
> 
> Hello everyone,
> 
> One major pain point I've run into with Swift is the inability to evaluate 
> the case of an enum that has associated values in a way that just returns a 
> bool. We've been given the ability in a switch statement:
> 
> enum Enum {
>case a(param: String)
>case b(param: String)
> }
> 
> let enumeration: Enum = a(param: "Hi")
> switch enumeration {
> case a:
>   // Do something
> case b:
>   // Do something
> }
> 
> We'e been given the ability in the context of an if statement:
> 
> enum Enum {
>case a(param: String)
>case b(param: String)
> }
> 
> let enumeration: Enum = a(param: "Hi")
> 
> if case .a = enumeration { 
> // Do something
> }
> 
> But without a basic was of getting a bool for if an enum is a given case, 
> here's a list of things I can't do:
> 
> Where statements:
> 
> enum Enum {
>case a(param: Enum2)
>case b(param: Enum2)
> }
> 
> enum Enum2 {
> case c(param: String)
> case d(param: String)
> }
> 
> let enumeration: Enum = a(param: "Hi")
> switch enumeration {
> case a(let inner) where [INNER CASE IS .c]
> }
> 
> -
> 
> Filter an array for a certain case:
> 
> Expertly explained by Erica Sadun here: 
> http://ericasadun.com/2017/01/31/challenge-filtering-associated-value-enumeration-arrays/
>  
> 
> 
> -
> 
> Nicely set a UIButton to hidden if an enum is a certain case:
> 
> enum State {
> case `default`
> case searching(results: [Result])
> }
> 
> myButton.isHidden = [STATE IS .searching]
> 
> -
> 
> I've run into this issue a ton of times because I tend to represent my views 
> a State enums. I haven't seen anything on the board for plans for solving 
> this issue, thought. Has there been any discussion about addressing it? 
> Ideally I'd be able to do this:
> 
> enum Enum {
>case a(param: String)
>case b(param: String)
> }
> 
> let enumeration: Enum = a(param: "Hi")
> 
> case .a = enumeration // Bool
> case .a(let param) = enumeration // Bool, assigns "Hi" to "param"
> 
> Thanks!
> Ethan
> 
> ___
> 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] Refining SE-0185: Should providing a custom == suppress the default hashValue?

2017-12-15 Thread Kevin Nattinger via swift-evolution
I’m skeptical that your use case is common enough to justify leaving open the 
glaring bug magnet that started this thread. Could you give an example of a 
common occurrence where it would be a significant improvement to explicitly 
write a *less precise* hash function that’s only “good enough” and still want 
the more precise full equality? 

TBH, I think contributors here are often too quick to demand padding the walls 
to protect the most incompetent of engineers from themselves, but I feel like 
the root proposal here is a good idea.


> On Dec 15, 2017, at 9:59 PM, Tony Allevato via swift-evolution 
>  wrote:
> 
> Those are valid concerns for hashing algorithms in general, but there's no 
> connection between that and a statement that an explicitly implemented 
> hashValue should also require an explicitly implemented ==. Requiring that 
> certainly doesn't make it less likely that people will run into the problem 
> you've described if they implement their own hashValue—if they implement it 
> poorly, it just means that the could also shoot themselves in the foot by 
> then being forced to also implement == and possibly doing it poorly.

IMO, it’s far easier to implement hashValue poorly, so I think reminding the 
dev they need to think about `==` too is more helpful than not. I’m not often 
in favor of the padded cell, but I would even consider a proposal to emit a 
warning if fields read in `==` is a strict subset of fields read in `hashValue`.

> 
> 
> 
> On Fri, Dec 15, 2017 at 9:53 PM Howard Lovatt  > wrote:
> I would say it is an advanced use because it is an optimisation and in 
> addition an optimisation that requires a lot of knowledge of the fields to be 
> certain that a reduced hash is going to be good enough. 
> 
> The optimisation doesn’t have a great history, for example in Java they used 
> to hash only the 1st 6 characters of a string. However this was exploited in 
> denial of service attacks that generated a vast number of strings with the 
> same hash value, i.e same 1st 6 characters, that then overwhelmed the 
> dictionary (map in Java) used in the web server software to store logins. 
> 
> So it wouldn’t be something I would encourage people to do or even worse do 
> by accident. 
> 
> 
> -- Howard.
> 
> On 16 Dec 2017, at 3:36 pm, Tony Allevato  > wrote:
> 
>> 
>> 
>> On Fri, Dec 15, 2017 at 6:41 PM Howard Lovatt > > wrote:
>> I think that is an advanced use, rather than a common use. I would prefer 
>> that to be something you manually code. 
>> 
>> But why? Why should implementing a subset of fields for hashValue require a 
>> developer to also manually implement == when the default synthesized version 
>> would be perfectly fine? The relationship between Equatable and Hashable 
>> does not go both ways.
>> 
>> In fact, requiring that they do so is *more* error prone because now they're 
>> being forced to implement something that the compiler would have otherwise 
>> generated for them.
>> 
>>  
>> 
>> 
>> -- Howard.
>> 
>> On 16 Dec 2017, at 7:08 am, Tony Allevato > > wrote:
>> 
>>> 
>>> 
>>> On Fri, Dec 15, 2017 at 11:39 AM Howard Lovatt via swift-evolution 
>>> > wrote:
>>> +1
>>> I think the simple solution of if you provide either == or hashValue you 
>>> have to provide both is the best approach. Good catch of this bug.
>>> -- Howard.
>>> 
>>> That would be a significant usability hit to a common use case. There are 
>>> times where a value is composed of N fields where N is large-ish, and 
>>> equality is dependent on the values of all N fields but the hash value only 
>>> needs to be "good enough" by considering some subset of those fields (to 
>>> make computing it more efficient).
>>> 
>>> That still satisfies the related relationship between == and hashValue, but 
>>> a user wanting to explicitly implement a more efficient hashValue should 
>>> *not* necessarily be required to explicitly write the same == that would be 
>>> synthesized for them in that case.
>>> 
>>>  
>>> 
>>> > On 16 Dec 2017, at 6:24 am, Daniel Duan via swift-evolution 
>>> > > wrote:
>>> >
>>> > +1. The proposal wasn’t explicit enough to have either supported or be 
>>> > against this IMO. It’s a sensible thing to spell out.
>>> >
>>> > Daniel Duan
>>> > Sent from my iPhone
>>> >
>>> >> On Dec 15, 2017, at 9:58 AM, Joe Groff via swift-evolution 
>>> >> > wrote:
>>> >>
>>> >> SE-0185 is awesome, and brings the long-awaited ability for the compiler 
>>> >> to provide a default implementation of `==` and `hashValue` when you 
>>> >> don't provide one 

Re: [swift-evolution] [Idea] [Pitch] Add `match` statement as `switch`-like syntax alternative to `if case` pattern matching

2017-11-18 Thread Kevin Nattinger via swift-evolution
There have been earlier suggestions for an alternative to `fallthrough` that 
would continue matching cases; I think that is much more likely to get support 
than a whole new construct with only a subtle difference from an existing 
one—would that be an acceptable alternative to you?

> On Nov 17, 2017, at 12:06 PM, Peter Kamb via swift-evolution 
>  wrote:
> 
> ## Title
> 
> Add `match` statement as `switch`-like syntax alternative to `if case` 
> pattern matching
> 
> ## Summary:
> 
> The syntax of the `switch` statement is familiar, succinct, elegant, and 
> understandable. Swift pattern-matching tutorials use `switch` statements 
> almost exclusively, with small sections at the end for alternatives such as 
> `if case`.
> 
> However, the `switch` statement has several unique behaviors unrelated to 
> pattern matching. Namely:  
> 
>  - Only the *first* matching case is executed. Subsequent matching cases are 
> not executed.
>  - `default:` case is required, even for expressions where a default case 
> does not make sense.
> 
> These behaviors prevent `switch` from being used as a generic 
> match-patterns-against-a-single-expression statement.
> 
> Swift should contain an equally-good pattern-matching statement that does not 
> limit itself single-branch switching.
> 
> ## Pitch:
> 
> Add a `match` statement with the same elegant syntax as the `switch` 
> statement, but without any of the "branch switching" baggage.
> 
> ```
> match someValue {
> case patternOne:
> always executed if pattern matches
> case patternTwo:
> always executed if pattern matches
> }
> ```
> 
> The match statement would allow a single value to be filtered through 
> *multiple* cases of pattern-matching evaluation.
> 
> ## Example:
> 
> ```
> struct TextFlags: OptionSet {
> let rawValue: Int
> static let italics = TextFlags(rawValue: 1 << 1)
> static let bold= TextFlags(rawValue: 1 << 2)
> }
> 
> let textFlags: TextFlags = [.italics, .bold]
> 
> 
> 
> // SWITCH STATEMENT
> switch textFlags {
> case let x where x.contains(.italics):
> print("italics")
> case let x where x.contains(.bold):
> print("bold")
> default:
> print("forced to include a default case")
> }
> // prints "italics"
> // Does NOT print "bold", despite .bold being set.
> 
> 
> 
> // MATCH STATEMENT
> match textFlags {
> case let x where x.contains(.italics):
> print("italics")
> case let x where x.contains(.bold):
> print("bold")
> }
> // prints "italics"
> // prints "bold"
> ```
> 
> ## Enum vs. OptionSet
> 
> The basic difference between `switch` and `match` is the same conceptual 
> difference between `Emum` and an `OptionSet` bitmask.
> 
> `switch` is essentially designed for enums: switching to a single logical 
> branch based on the single distinct case represented by the enum.
> 
> `match` would be designed for OptionSet bitmasks and similar constructs. 
> Executing behavior for *any and all* of the following cases and patterns that 
> match.
> 
> The programmer would choose between `switch` or `match` based on the goal of 
> the pattern matching. For example, pattern matching a String. `switch` would 
> be appropriate for evaluating a String that represents the rawValue of an 
> enum. But `match` would be more appropriate for evaluating a single input 
> String against multiple unrelated-to-each-other regexes.
> 
> ## Existing Alternatives
> 
> `switch` cannot be used to match multiple cases. There are several ways "test 
> a value against multiple patterns, executing behavior for each pattern that 
> matches", but none are as elegant and understandable as the switch statement 
> syntax.
> 
> Example using a string of independent `if case` statements:
> 
> ```
> if case let x = textFlags, x.contains(.italics) {
> print("italics")
> }
> 
> if case let x = textFlags, x.contains(.bold) {
> print("bold")
> }
> ```
> 
> ## `match` statement benefits:
> 
>  - Allow filtering a single object through *multiple* cases of pattern 
> matching, executing *all* cases that match.
> 
>  - A syntax that exactly aligns with the familiar, succinct, elegant, and 
> understandable `switch` syntax.
> 
> - The keyword "match" highlights that pattern matching will occur. Would be 
> even better than `switch` for initial introductions to pattern-matching.
> 
>  - No need to convert between the strangely slightly different syntax of 
> `switch` vs. `if case`, such as `case let x where x.contains(.italics):` to 
> `if case let x = textFlags, x.contains(.italics) {`
> 
>  - Bring the "Expression Pattern" to non-branch-switching contexts. 
> Currently: "An expression pattern represents the value of an expression. 
> Expression patterns appear only in switch statement case labels."
> 
>  - A single `match controlExpression` at the top rather than 
> `controlExpression` being repeated (and possibly changed) in every single `if 
> case` statement.
> 
>  - Duplicated `controlExpression` is an opportunity 

Re: [swift-evolution] [Accepted and Focused Re-review] SE-0187: Introduce Sequence.filterMap(_:)

2017-11-16 Thread Kevin Nattinger via swift-evolution
As far as the Sequence overloads: I really, really think we should go a step 
beyond renaming and separate the functions into the underlying operations. 
FlatMap has three separate and orthogonal effects, so it should be split into 
three functions—flatten, map, and dropNil. Map already exists, obviously, but 
flatten and dropNil (or compact[ed], as I've seen suggested) are independently 
useful—I've used `.flatMap { $0 }` several times, and I've written my own 
`flatten` because I didn't actually realize there was a separate overload for 
that (I don't want to sound rude to the Apple devs who decided on that, but… 
why on earth was an already confusing name overloaded with unrelated 
functionality instead of using the term of art?). 

For Optional, I suggest mapValue.

> On Nov 16, 2017, at 8:11 AM, Erica Sadun via swift-evolution 
>  wrote:
> 
> 
> I like `mapSome`:
> 
> * `mapSome` uses conventional Swift terminology. 
> * It makes the outcome and expectations clear. 
> * As a bonus, it combines the English meaning of "some" ("map across some of 
> these items", as in creating a filtered result) and the `Optional` case name. 
> 
> In response to John's "mapSome and especially mapNonNil both sound to me like 
> they only map the non-nil values in the source sequence.", I'd respond that   
> the mode of action is:
> 
> 1. apply the function
> 2. retrieve `some` cases 
> 
> Selecting `mapSome` reflects those two stages. There is, however, Kevin's 
> (sound) point against that it "sounds like it takes a sequence of optionals 
> and only modifies the non-nil values", but I still like it.  Some of the 
> suggestions built around unwrapping address John's concern, for example 
> `mapUnwrapped` but fail to distinguish between the `some` and `nil` cases, 
> suggesting perhaps a catastrophic outcome for nil values.
> 
> I could live with many of the other names but I dislike `compact` (it has no 
> precedent, sets an expectation of the implementation which may not match 
> reality). Similarly `mapReduce` or `mapReducing` (which I prefer to 
> `reduceMap`) may overburden the expectation of the existing `reduce`, where a 
> user thinks prior results feed into the output, which they don't.  I 
> moderately like `mapSelective` (over `selectiveMap`) but I like it less than 
> `filterMap`, `mapFiltering`, or `mapFiltered` and `mapSome`, all of which use 
> Swift terms of art in their naming. (Also note Gwendal's finding that as a 
> term of art, it has "a different signature, and a different meaning" in 
> RxSwift.)
> 
> Summary:
> 
> * I like `mapSome`
> * I'm fine with a `filter` variation, of which I prefer `mapFiltered`
> 
> -- E, former supporter of `filterMap` before `mapSome` entered her awareness
> 
> 
>> On Nov 15, 2017, at 2:15 PM, Ben Cohen via swift-evolution 
>> > wrote:
>> 
>> I continue to favour mapSome, since it’s both literally and figuratively 
>> what it does, but appreciate that exposing the name of the Optional.some 
>> case isn’t to everyone’s taste.
>> 
>>> On Nov 15, 2017, at 12:55 PM, John McCall via swift-evolution 
>>> > wrote:
>>> 
>>> Hello, Swift Community!
>>> 
>>> The initial review of "SE-0187: Introduce Sequence.filterMap(_:)" ran 
>>> through yesterday, November 14th, 2017.  The proposal is available here:
>>> 
>>> https://github.com/apple/swift-evolution/blob/master/proposals/0187-introduce-filtermap.md
>>>  
>>> 
>>> 
>>> There was a significant amount of discussion, and people came down with 
>>> reasonable arguments both for and against the proposal.  After reviewing 
>>> that feedback, the core team feels that the central question is whether 
>>> Swift benefits from overloading flatMap in this way.  There is a reasonable 
>>> argument that an Optional is a sort of container, and therefore it makes 
>>> sense to "flatten" that container into a surrounding container.  But Swift 
>>> has resisted applying that interpretation in its library design; for 
>>> example, you cannot directly iterate an Optional or append its contents to 
>>> an Array.  In general, we feel that using different operations for working 
>>> with Optionals tends to make code easier to both write and understand, 
>>> especially given the existence of implicit optional promotion, which we 
>>> cannot eliminate or easily suppress based on the context.  On reflection, 
>>> we think it was a mistake to use the same name in the first place, and 
>>> there is no better time to fix a mistake than now.
>>> 
>>> While we accept that this will cause some amount of "code churn" for 
>>> developers when they adopt Swift 5, the required change is a simple rename 
>>> that should be painless to automatically migrate.  Of course, sample code 
>>> on the internet will become obsolete, but 

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-17 Thread Kevin Nattinger via swift-evolution
So, what I'm getting from this explanation is that `Equatable` is meaningless 
on its own; each class needs to document exactly what  "substitutability" means 
as implemented, and any code that uses `==` needs to check the documentation 
for that specific class and make sure the intended use ("context," as you say) 
aligns with the class's definition.

>>> 
>>> Contrived Example: Two Lorem Ipsum generators are the same generator 
>>> (referentially equal, substitutable for the purposes of my library), but 
>>> they sample the user’s current battery level (global state) each time they 
>>> produce text to decide how fancy to make the faux Latin. They’re 
>>> substitutable, but don’t generate the same sequence.
>> 
>> Evidently I disagree with your definition of "substitutable." How can you 
>> say one thing can be substituted for another when doing so gives a different 
>> result?
>> 
> 
> They are substitutable for the purposes of certain operations. The key 
> question is “what” gives a different result.
> 
> Sets are primarily about membership, and equal sets are substitutable (hand 
> wavy) for Set-like purposes. But, two equal Sets are not substitutable for 
> iteration purposes unless they produce the same elements in the same order. 
> This latter requirement is far less important than the former for Sets, but 
> can still come up in generic contexts.
> 
> Two Lorem Ipsum generators could be equal in that they are substitutable for 
> (hand wavy) faux-Latin generation purposes, even if the sequence of generated 
> characters happens to differ.

Hmm, I… guess I could see randomized generators comparing == because their 
public configuration is the same, just not the implementation detail of their 
RNG states.  Not sure I'd implement it that way myself—perhaps I just take the 
"substitutability" more seriously than some.

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-17 Thread Kevin Nattinger via swift-evolution

> On Oct 17, 2017, at 11:47 AM, Michael Ilseman <milse...@apple.com> wrote:
> 
> 
> 
>> On Oct 17, 2017, at 10:15 AM, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>>> Because, in my analysis, the problem is that the method is incorrectly 
>>> named. The problem affects all types that conform to Sequence and not just 
>>> Set and Dictionary; elementsEqual is a distinct function from ==, and it 
>>> must either continue to be distinct or cease to exist, but its name does 
>>> nothing to clarify any distinction.
>> 
>> In my analysis, the problem is the method's implementation. As I see it, the 
>> only use for `elementsEqual` is as a replacement for `==` when two objects 
>> are different types (or not known to be the same)—equal elements, and IF the 
>> sequences have an order, in the same order. Could you provide an example 
>> where `elementsEqual` randomly returning either true or false depending on 
>> internal state alone is a legitimate and desirable result?
>> 
> 
> It doesn’t randomly return true or false, it consistently returns true or 
> false for the *same* pair of Sequences. What *same* means, of course, is 
> complicated and exists at two levels (as we have two ways of talking about 
> *same*). 

I didn't mean literally random, but the result for any two equal sets is 
unpredictable and depends on implementation details.

> 
> I apologize for not reading every email in depth in this thread (they are 
> coming in faster than I can parse them), but let me try to present motivation 
> for this and hopefully provide more shared understanding.
> 
> We have two forms of equality we’re talking about: equality of Sequence and 
> equality of the elements of Sequences in their respective ordering. `==` 
> covers the former, and I’ll use the existing (harmful) name of 
> `elementsEqual` for the latter.
> 
> `==` conveys substitutability of the two Sequences. This does not necessarily 
> entail anything about their elements, how those elements are ordered, etc., 
> it just means two Sequences are substitutable. `elementsEqual` means that the 
> two Sequences produce substitutable elements. These are different concepts 
> and both are independently useful.
> 
> Cases:
> 
> 1. Two Sequences are substitutable and produce substitutable elements when 
> iterated. `==` and `elementsEqual` both return true. 
> 
> Example: Two arrays with the same elements in the same order.
> 
> 
> 2. Two Sequences are substitutable, but do not produce substitutable elements 
> when iterated. `==` returns true, while `elementsEqual` returns false.
> 
> Example: Two Sets that contain the same elements but in a different order.
> 
> Contrived Example: Two Lorem Ipsum generators are the same generator 
> (referentially equal, substitutable for the purposes of my library), but they 
> sample the user’s current battery level (global state) each time they produce 
> text to decide how fancy to make the faux Latin. They’re substitutable, but 
> don’t generate the same sequence.

Evidently I disagree with your definition of "substitutable." How can you say 
one thing can be substituted for another when doing so gives a different result?

> 
> 
> 3. Two Sequences are not substitutable, but produce substitutable elements 
> when iterated. `==` returns false, while `elementsEqual` returns true.
> 
> Example: Consider two sequences that have differing identity. `==` operates 
> on an identity level, `elementsEqual` operates at an element level.
> 
> Contrived Example: InfiniteMonkeys and Shakespeare both produce the same 
> sonnet, but they’re not substitutable for my library’s purposes. 

The way I see it, this is exactly the reason for this function—determining 
whether two objects give the same sequence without regards to their types.

> 
> 
> 4. Two Sequences are not substitutable and don’t produce substitutable 
> elements when iterated. `==` and `elementsEqual` both return false.
> 
> Example: `[1,2,3]` compared to `[4,5,6]`
> 
> 
> It is true that situations #2 and #3 are a little harder to grok, but they 
> are what illustrate the subtle difference at hand. I think situation #2 is 
> the most confusing, and has been the primary focus of this thread as Set 
> exists and exhibits it.

Indeed. My opinion is that #2 is not just confusing, but an entirely invalid 
result/state. 

> 
> 
> Now, onto naming. `elementsEqual` is a very poor choice of name for the 
> concept of equality of elements in their respective orderings, as it doesn’t 
> highlight the “in their respective orderings” part. `lexicographicallyEqual` 
>

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-17 Thread Kevin Nattinger via swift-evolution
>>> set.elementsEqual(set)
>> 
>> I see why that would work (thanks to Set being a collection vs a sequence), 
>> but it still feels like a hack.  I definitely wouldn’t want to be 
>> maintaining code with that in it. Especially when compared to something like:
>> 
>>  set.contains(where: {$0.isNaN})
>> 
>> The purpose of protocols is to enable useful generic code. You cannot use 
>> isNaN for code that works on generic Collection, or for that matter, even 
>> code that works on Set where Element : Numeric.
>> 
>> Much generic code (for example, generic sorting) easily blows up when 
>> encountering NaN. If you want an algorithm that is robust enough to handle 
>> (or at least reject) that scenario, then you will need to check for it. It 
>> is not a “hack” but a very common and accepted way of determining the 
>> presence of NaN.
> 
> Just because a hack is commonly accepted or common doesn’t mean it isn’t a 
> hack.
> 
> It’s not a “hack.” NaN is required by IEEE fiat not to be equivalent to 
> itself. Asking whether a value is reflexively equivalent to itself is 
> guaranteed to be sufficient to detect the presence of NaN in all 
> IEEE-compliant contexts, which is to say all past, present, and future 
> versions of Swift.

- while `a.elementsEqual(a)` returning true precludes the presence of a nan, 
returning false is not a guarantee there is a NaN—at least the way you have 
insist this method should work. The isNaN version is correct in all cases.
- It's a great deal less readable and obvious than the `where { $0.isNaN }` 
version, so while the term "hack" is arguably not correct (assuming you only 
need to disprove a NaN and not prove one exists), it is certainly not the most 
readable way.
- IEEE says Float.nan == Float.nan must be false; I'm pretty sure the IEEE spec 
doesn't say anything about how Swift Sequences must implement `elementsEqual`.

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-17 Thread Kevin Nattinger via swift-evolution

> On Oct 17, 2017, at 10:36 AM, Adam Kemp  wrote:
> 
> 
>> On Oct 17, 2017, at 10:00 AM, Kevin Nattinger > > wrote:
>> 
>> Once we allow covariant functions to satisfy protocol requirements and have 
>> generalized existentials and recursive protocol requirements, wouldn't we be 
>> able to update thusly:
>> 
>> protocol Unordered {
>>  func map(…) -> Any
>> }
>> protocol Ordered: Unordered {
>>  func map(…) -> Any
>> }
>> 
> 
> Now apply that to every order-preserving function that takes a Sequence and 
> returns another Sequence. You’ve moved the burden from users of API to 
> implementers of API. It reminds me of the const/non-const split that C++ 
> developers have to deal with, where a lot of functions end up being 
> implemented twice so that you can have a const version and a non-const 
> version (generally one just calls the other). It’s a pain. I don’t want that 
> when working with Sequences. I don’t think it’s worth it. And FWIW, when I 
> was programming in C# I wrote functions that took an IEnumerable and 
> return another IEnumerable very often. It’s a powerful feature that would 
> have been ruined by a change like this.

The idea is that covariance would mean you only need to implement the function 
once.

> 
>> As I've been saying all along, elementsEqual returning a functionally random 
>> result when an unordered type is involved is a problem.
> 
> In theory. Where is the evidence that this leads to a significant number of 
> real-world bugs? All you’ve done is describe a conceptual problem, but you 
> haven’t connected the dots to real-world problems. Again, I can point to 
> .Net, which has a much larger community of developers who have been working 
> with the same “problem” since version 2.0 released in 2005. If this is a 
> significant source of bugs then there should be evidence of that. Where is 
> that evidence?

If there are no real-world problems, why do we feel the need to change the 
function name in the first place?

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-17 Thread Kevin Nattinger via swift-evolution

> On Oct 16, 2017, at 1:29 PM, Adam Kemp via swift-evolution 
>  wrote:
> 
> 
> 
>> On Oct 16, 2017, at 12:35 PM, Thorsten Seitz via swift-evolution 
>> > wrote:
>> 
>> IMHO `elementsEqual` provides a nice example for a method which only makes 
>> sense on something meaningfully ordered:
>> What is the use case for `elementsEqual` that works with a Set?
> 
> There may not be one, but here’s the problem:
> 
> 1. It’s generally useful for Set to conform to a protocol that allows you to 
> iterate over its elements.
> 2. It’s generally useful to be able to ask if two objects that you can 
> iterate over are equal by comparing the elements in the order that they’re 
> iterated over.
> 
> The argument being made is that these two protocols should be different, but 
> I don’t think the proponents of that idea have fully thought through what 
> that would mean in practice. Consider a function like map, which takes a 
> Sequence and produces another Sequence. This function is useful for both 
> ordered and unordered elements so it would have to be defined in terms of the 
> looser (unordered) type, which means its output type would be unordered. 
> Imagine starting with an ordered enumerable and calling map on it. What’s the 
> result? An unordered enumerable (the return type of map would be unordered to 
> match its input type). Now you can’t use any of the methods that require the 
> stricter (ordered) protocol on the result, even though you haven’t actually 
> lost the order. You would have to do something to fix up the type and make 
> the compiler see it as ordered again. Maybe there’s an asOrdered method or 
> something. Imagine having to sprinkle that throughout your code just to make 
> things compile. Does that sound like a usable API?
> 
> 
> let people:[Person] = [] // Ordered
> let orderedNames:[String] = [] // Ordered
> let names = people.map { $0.fullName } // Result is unordered
> return names.elementsEqual(orderedNames) // compile error: names is unordered
> // Maybe: return names.asOrdered().elementsEqual(orderedNames)?
> 
> Avoiding this mess would require overloading such that every function that 
> supports either ordered or unordered would have to be written both ways, 
> which would just be a different mess.

That is a great point. Once we allow covariant functions to satisfy protocol 
requirements and have generalized existentials and recursive protocol 
requirements, wouldn't we be able to update thusly:

protocol Unordered {
func map(…) -> Any
}
protocol Ordered: Unordered {
func map(…) -> Any
}

?

Or the following; it also requires generalized existentials and recursive 
protocol requirements but not covariance; though I can imagine people arguing 
against introducing more associated types:
 
protocol Unordered {
associatedtype MapResultType: Unordered
func map(…) -> Any
}

This would even allow an ordered collection to map to an unordered one or 
vice-versa.  Maybe a collection type that spits out an ordered list when 
mapping to Comparables.
(n.b. the more I think about it, the more I like this option. Where are our 
existentials and recursive requirements? :) )

In this case we wouldn't even need an Ordered override; using concrete classes 
directly it would just work, and a function that requires an ordered result 
could specify it as any other constraint just as you do today:

func foo(in seq: O) where O.Element == Int, O.MapResultType: 
Ordered {
let orderedMapping = seq.map { $0 + 1 } // type = Any
…
}

I'd be ok with `map` and `filter` keeping their array returns (and that's 
what's in my original email about this) until we get the language features 
needed to support these. And I think we'd want to revisit the definitions of 
much of what is currently Sequence once we get these language features anyway.

> 
> All of that would be to solve a problem that in practice doesn’t seem to 
> really cause any problems. I’m not aware of any evidence to suggest that this 
> type causes a significant number of bugs, and we have another 
> language/runtime (C#/.Net) with a large number of active developers and code 
> bases with the same design and the same lack of evidence of a problem.

As I've been saying all along, elementsEqual returning a functionally random 
result when an unordered type is involved is a problem. At the least, we should 
make an OrderedSequence (conforming to Sequence, but could even be otherwise 
empty), move at least elementsEqual and lexicographicallyPrecedes to functions 
or extensions on that, and conform the appropriate stdlib types. Which would 
obviously not include Set or Dictionary. 

> It seems like we’re being asked to make the library significantly harder to 
> work with in order to solve a set of bugs that, as far as I can tell, doesn’t 
> really exist in practice. I think in order to even consider this we would 
> need to see 

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-17 Thread Kevin Nattinger via swift-evolution
> Because, in my analysis, the problem is that the method is incorrectly named. 
> The problem affects all types that conform to Sequence and not just Set and 
> Dictionary; elementsEqual is a distinct function from ==, and it must either 
> continue to be distinct or cease to exist, but its name does nothing to 
> clarify any distinction.

In my analysis, the problem is the method's implementation. As I see it, the 
only use for `elementsEqual` is as a replacement for `==` when two objects are 
different types (or not known to be the same)—equal elements, and IF the 
sequences have an order, in the same order. Could you provide an example where 
`elementsEqual` randomly returning either true or false depending on internal 
state alone is a legitimate and desirable result?

> 
> Thanks,
> Jon
> ___
> 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] [Draft] Rename Sequence.elementsEqual

2017-10-16 Thread Kevin Nattinger via swift-evolution

> On Oct 16, 2017, at 1:08 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> 
> On Mon, Oct 16, 2017 at 13:15 David Sweeris  > wrote:
> 
> On Oct 16, 2017, at 09:21, Michael Ilseman  > wrote:
> 
>> 
>> 
>>> On Oct 16, 2017, at 8:46 AM, David Sweeris via swift-evolution 
>>> > wrote:
>>> 
>>> 
>>> On Oct 16, 2017, at 07:20, Xiaodi Wu via swift-evolution 
>>> > wrote:
>>> 
 
 On Mon, Oct 16, 2017 at 05:48 Jonathan Hull > wrote:
 
> On Oct 15, 2017, at 9:58 PM, Xiaodi Wu  > wrote:
> 
> On Sun, Oct 15, 2017 at 8:51 PM, Jonathan Hull  > wrote:
> 
>> On Oct 14, 2017, at 10:48 PM, Xiaodi Wu > > wrote:
  That ordering can be arbitrary, but it shouldn’t leak internal 
 representation such that the method used to create identical things 
 affects the outcome of generic methods because of differences in 
 internal representation.
 
 
>  It would be better to say that the iteration order is well-defined. 
> That will almost always mean documented, and usually predictable 
> though obviously e.g. RNGs and iterating in random order will not be 
> predictable by design.
> 
>> That's actually more semantically constrained than what Swift calls 
>> a `Collection` (which requires conforming types to be multi-pass 
>> and(?) finite). By contrast, Swift's `SpongeBob` protocol explicitly 
>> permits conforming single-pass, infinite, and/or unordered types. 
> 
> I think you’re talking about Sequence here, I’ve lost track of your 
> nonsense by now. Yes, the current Swift protocol named Sequence 
> allows unordered types. You seem to keep asserting that but not 
> actually addressing my argument, which is that allowing Sequences to 
> be unordered with the current API is undesired and actively harmful, 
> and should therefore be changed.
> 
> What is harmful about it?
 
 After thinking about it, I think the harmful bit is that unordered 
 sequences are leaking internal representation (In your example, this 
 is causing people to be surprised when two sets with identical 
 elements are generating different sequences/orderings based on how 
 they were created).  You are correct when you say that this problem is 
 even true for for-in.
 
 I would not say it is a problem. Rather, by definition, iteration 
 involves retrieving one element after another; if you're allowed to do 
 that with Set, then the elements of a Set are observably ordered in 
 some way. Since it's not an OrderedSet--i.e., order doesn't 
 matter--then the only sensible conclusion is that the order of 
 elements obtained in a for...in loop must be arbitrary. If you think 
 this is harmful, then you must believe that one should be prohibited 
 from iterating over an instance of Set. Otherwise, Set is inescapably 
 a Sequence by the Swift definition of Sequence. All extension methods 
 on Sequence like drop(while:) are really just conveniences for common 
 things that you can do with iterated access; to my mind, they're 
 essentially just alternative ways of spelling various for...in loops.
>>> 
>>> I think an argument could be made that you shouldn’t be able to iterate 
>>> over a set without first defining an ordering on it (even if that 
>>> ordering is somewhat arbitrary).  Maybe we have something like a 
>>> “Sequenc(e)able” protocol which defines things which can be turned into 
>>> a sequence when combined with some sort of ordering.  One possible 
>>> ordering could be the internal representation (At least in that case we 
>>> are calling it out specifically).  If I had to say 
>>> “setA.arbitraryOrder.elementsEqual(setB.arbitraryOrder)” I would 
>>> definitely be less surprised when it returns false even though setA == 
>>> setB.
>>> 
>>> Well, that's a totally different direction, then; you're arguing that 
>>> `Set` and `Dictionary` should not conform to `Sequence` altogether. 
>>> That's fine (it's also a direction that some of us explored off-list a 
>>> while ago), but at this point in Swift's evolution, realistically, it's 
>>> not within the realm of possible changes.
>> 
>> I am actually suggesting something slightly different.  Basically, Set 
>> and 

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-16 Thread Kevin Nattinger via swift-evolution

> On Oct 16, 2017, at 11:23 AM, David Sweeris via swift-evolution 
>  wrote:
> 
> 
> On Oct 16, 2017, at 10:42, BJ Homer via swift-evolution 
> > wrote:
> 
>>> On Oct 16, 2017, at 8:20 AM, Thorsten Seitz via swift-evolution 
>>> > wrote:
>>> 
 Am 16.10.2017 um 07:19 schrieb Xiaodi Wu >:
>>> 
 What useful generic algorithms would this protocol support that are not 
 already possible?
>>> 
>>> It would allow expressing generic algorithms depending on an order.
>>> 
>>> -Thorsten
>> 
>> We can already express generic algorithms that depend on an order—any 
>> generic algorithm that works on a Sequence works on something that is 
>> ordered. A Swift Set has an undefined order right now, but a generic 
>> algorithm working on any arbitrary Sequence likely doesn’t care about what 
>> the order, just that an order exists. And a Swift Set does indeed have an 
>> order. If you have a generic algorithm that only works on inputs sorted in a 
>> particular manner, then you’ve likely either documented that or added a 
>> “sortedBy” parameter. Otherwise, you probably just want to be able to 
>> iterate through everything.
>> 
>> Let’s assume, though, that you wanted to write an algorithm that works only 
>> on MeaningfullyOrdered inputs. 
>> 
>> func extractInfo(_ input: T) { }
>> extractInfo(someArray)
>> 
>> What stops the caller from simply wrapping the Set in an Array?
>> 
>> extractInfo(Array(someSet))
>> 
>> The Array constructed here is going to reflect the arbitrary ordering 
>> provided by Set, but as far as the type system is concerned, the input is an 
>> Array, which is certainly meaningfully-ordered. Have we gained anything by 
>> requiring the caller to wrap the input in an array? We’ve made the call site 
>> a bit more awkward, and we’ve lost a bit of performance. We certainly need 
>> to be able to convert Sets in to Arrays; to eliminate that would be 
>> massively source-breaking, and it’s not clear that allowing that conversion 
>> is actively harmful, so it’s unlikely to change in Swift 5.
> 
> Should/could we just rename `Set` to `UniquedArray` or something like that? 
> This is starting to feel a bit like the access control debate.

So essentially convert Set to OrderedSet and not offer a theoretical unordered 
Set? I think that would be acceptable (if we apply it to dictionaries as well), 
BUT that doesn't address the more general case of other, potentially custom 
unordered Sequences.

> 
> - 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] [Draft] Rename Sequence.elementsEqual

2017-10-16 Thread Kevin Nattinger via swift-evolution

> On Oct 16, 2017, at 10:43 AM, BJ Homer via swift-evolution 
>  wrote:
> 
>> On Oct 16, 2017, at 8:20 AM, Thorsten Seitz via swift-evolution 
>> > wrote:
>> 
>>> Am 16.10.2017 um 07:19 schrieb Xiaodi Wu >> >:
>> 
>>> What useful generic algorithms would this protocol support that are not 
>>> already possible?
>> 
>> It would allow expressing generic algorithms depending on an order.
>> 
>> -Thorsten
> 
> We can already express generic algorithms that depend on an order—any generic 
> algorithm that works on a Sequence works on something that is ordered. A 
> Swift Set has an undefined order right now, but a generic algorithm working 
> on any arbitrary Sequence likely doesn’t care about what the order, just that 
> an order exists. And a Swift Set does indeed have an order. If you have a 
> generic algorithm that only works on inputs sorted in a particular manner, 
> then you’ve likely either documented that or added a “sortedBy” parameter. 
> Otherwise, you probably just want to be able to iterate through everything.
> 
> Let’s assume, though, that you wanted to write an algorithm that works only 
> on MeaningfullyOrdered inputs. 
> 
> func extractInfo(_ input: T) { }
> extractInfo(someArray)
> 
> What stops the caller from simply wrapping the Set in an Array?
> 
> extractInfo(Array(someSet))
> 
> The Array constructed here is going to reflect the arbitrary ordering 
> provided by Set, but as far as the type system is concerned, the input is an 
> Array, which is certainly meaningfully-ordered. Have we gained anything by 
> requiring the caller to wrap the input in an array?

We force the user to acknowledge that the unspecified order is acceptable to 
them, as opposed to sorting. Much like the `uniquingKeysWith` argument on 
Dictionary.init(keysAndValues:uniquingKeysWith:). That one even has a sane 
default behavior used in many other languages (`{$1}`) and still doesn't offer 
that as a default; whereas a set's iteration order has no sane default. I think 
it would even be acceptable (or even desired) to have the set's Iterator be 
MeaningfullyOrdered, so the user could bypass the array and use 
`someSet.makeIterator()`, which would probably have little if any performance 
or memory overhead.

> We’ve made the call site a bit more awkward, and we’ve lost a bit of 
> performance. We certainly need to be able to convert Sets in to Arrays; to 
> eliminate that would be massively source-breaking, and it’s not clear that 
> allowing that conversion is actively harmful, so it’s unlikely to change in 
> Swift 5.
> 
> So I agree with Xiaodi; I don’t see what we would gain by splitting the 
> protocols, other than some conceptual purity.

Conceptual purity is, e.g. why protocols with associated types are such a pain 
in the ass to work with. Sequence makes plenty of sense and is concise and 
clear (and used in, e.g. Java, C#), why should I spell it Any, or whatever it ends up being. 4 years into the 
language and two of the majorly touted benefits of the language (protocols and 
generics) play so poorly with each other that it is one of if not THE major 
pain point in the language. All because a couple people wanted conceptual 
purity.

I'm quite sure I've seen the conceptual purity argument used in favor of many 
other suggestions on this list, though I don't have the time to go through and 
find them.

> Some have expressed concern over the existence of someSet.first, but even if 
> we removed it, it would still be available as Array(someSet).first. And we 
> still haven't any examples of actual algorithms that would surprise the user 
> by behaving incorrectly when given an arbitrarily-ordered sequence, so it’s 
> hard to make the argument that this restriction is actively harmful.

equalElements(), the original motivation for this proposal, is actively harmful 
on unordered Sequences. On any two instances of any unordered Sequence that are 
`==`, it could come back true or false. And adding and removing an element to 
one of them (so the same instance is back in the same state), could change the 
result. I don't think anyone new to the language would expect that. 

> I agree that isOrderedEqual(to:) is a better name for elementsEqual()

Much more acceptable than the proposed name.

> 
> -BJ
> ___
> 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] [Draft] Rename Sequence.elementsEqual

2017-10-16 Thread Kevin Nattinger via swift-evolution
>> 
>> How is the iteration order of an unordered set or dictionary “publicly 
>> observable”? If either is implemented such that it can asynchronously 
>> optimize its storage (maybe by rebalancing a tree or merging two 
>> non-contiguous array segments or something), its iteration order could 
>> change without changing what values it contains. Seems like consecutive 
>> calls to “elementsEquals” (or whatever we’re calling it) should return the 
>> same answer, if we don’t add, remove, or mutate elements.
>> 
> 
> Sets are values. If you add, remove, or mutate any elements you have a 
> different Set and thus a potentially different ordering of elements.

An implementation detail. We could make it a class* and AFAICT that wouldn't 
break any guarantees on Sequence; and the argument applies equally well to any 
other unordered Sequence, which has no value type or semantics constraint.

*: obviously we won't, I don't think anyone is advocating that.

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-16 Thread Kevin Nattinger via swift-evolution
>> […]
>> Set conforming to Collection is even worse than just conforming to Sequence 
>> as a quote from the documentation shows: "In addition to the operations that 
>> collections inherit from the Sequence protocol, you gain access to methods 
>> that depend on accessing an element at a specific position in a collection."
>> Clearly the elements of a Set do not have specific positions.
>> 
> 
> That’s not at all clear to me, could you elaborate? My understanding is that 
> elements of Set definitely *do* have a position, and that’s why you can use 
> an index on a set to retrieve the element. The same index on the same set 
> retrieves the same element.

A Set only has "indices" because it confirms to a protocol where almost all the 
requirements are meaningless for an unordered collection. Or at best, for the 
same reason it has an "order": as a side-effect of the fact that it can be 
iterated over, you can give indices for each element on a specific iteration; 
those indices are meaningless for the set itself, and should not be used for 
anything but a full, order-independent iteration.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-15 Thread Kevin Nattinger via swift-evolution
> […]
> Swift's Sequence protocol does not require the order of iteration to "convey 
> any meaning"; it doesn't even require it to be deterministic.
> 

And that’s EXACTLY why none of the functions on Sequence should rely on the 
order conveying meaning.  `ElementsEqual` (for example) DOES rely on the order 
of iteration conveying a meaning not required by the protocol, and renaming it 
`lexicographicallyEquals` does not change that fact. Either Sequence needs to 
require a meaningful order or `elementsEqual` should be moved to a protocol 
that does.

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-15 Thread Kevin Nattinger via swift-evolution
> […]
> Sets, as a mathematical concept, have no intrinsic order. However, instances 
> of `Set`, which can be iterated over, *do* have at least one order which can 
> be said to be intrinsic in the following sense: as long as iteration is 
> possible, no API design can prevent that order from being observed and 
> associated with the instance. Put another way, if you can use an instance of 
> a type in a for...in loop, intrinsic to that functionality is a publicly 
> visible order.

You keep saying this, I keep saying it’s only a technical “order” that is an 
implementation detail and can’t be relied upon for anything and so we shouldn’t 
provide methods that rely on it. I think this part of the discussion has 
reached the “agree to disagree” stage.

> […]
> You’re a fan of the principal of least surprise. Tell me, which would be less 
> surprising: Set.dropFirst() actually drops a random element, or Set doesn’t 
> have a dropFirst()? And if you think dropFirst() removing an element at 
> random is not surprising, please explain why.
> 
> I think Set.dropFirst removing the first element that I observe on iteration 
> is the least surprising answer, because Swift tells me that the stdlib Set 
> models a set but that it is also a sequence.

Your logic is backwards. You’re saying it’s “least surprising” because that’s 
how it’s currently implemented, not that it should be implemented that way 
because it’s least surprising.

 […]
> 
> And that’s PRECISELY why lexicographicallyEqual does not make sense to apply 
> to unordered sets. There is no lexicographical comparison possible, so why do 
> you keep insisting they should have a method that falsely claims to 
> lexicographically compare them?
> 
> I agree! It doesn't make sense if no comparison is possible! But Swift tells 
> me that a `Set` is a `Sequence`!

You keep making the circular argument that a Set should do things because it 
currently does them. If you want to argue against changing things, argue that 
things shouldn’t be changed, not that the current implementation is correct 
because it is the current implementation.

> […]
> You will always have to account for this possibility, because Swift's 
> `Equatable` explicitly allows "special values" to be not equal to themselves. 
> This is, at least in part, in order to accommodate the IEEE decree that NaN 
> != NaN:

> 
> ```
> let x = [Double.nan]
> x.elementsEqual(x) // false
> ```

NaN is special, one-shot and unordered sequences are not. Unless you think that 
all unordered and single-pass sequences should compare false for 
`elementsEqual`, this is irrelevant for any sequence that doesn’t contain NaN 
and well-defined (false) for any that does.

> Changing this behavior is way beyond the scope of this thread (and has been 
> the topic of hours (actually, weeks and weeks) of fun on this list 
> previously).

Yes, I’ve seen the discussion on NaN and Comparable. It’s not the same 
discussion.

> […]
>> It would be better to say that the iteration order is well-defined. That 
>> will almost always mean documented, and usually predictable though obviously 
>> e.g. RNGs and iterating in random order will not be predictable by design.
> 
> Wouldn't it then suffice to document, say, that a set's iteration order is 
> the insertion order?

Now this actually gave me pause. I guess it does match what I said, but I still 
take issue with the fact that two Sets could compare `==` but not 
`elementsEqual`. I think that defining iteration order as insertion order adds 
a piece of publicly documented state that goes beyond what a Set really is. 
What you describe is really an OrderedSet, just without the random-access 
manipulation. I’ll have to mull this over to see if I can come up with a 
coherent and (more) specific requirement for what makes an Iterable a Sequence, 
since clearly “documented” isn’t enough.  Perhaps something along the lines 
that any two Sequences that compare equal must iterate the same.

> […]
> Apple documentation calls this one of the "order-dependent" methods. It is 
> surely acceptable for a type that conforms to an order-dependent protocol to 
> have methods that are order-dependent; they do, however, have to be clearly 
> order-dependent to avoid confusion on unordered types.

I’m not clear on what you’re trying to get across here. It seems you’re saying 
unordered types shouldn’t have order-dependent methods, which is exactly what 
I’ve been arguing.

>  [...]
> Then there are all the methods that imply a specific order of iteration. If 
> the “sequence” is unordered, who knows what you’ll get? It is incredibly easy 
> for an engineer to write a method that implicitly relies on a passed sequence 
> being intrinsically ordered and another engineer to pass it an unordered 
> “sequence.”  The first engineer could neglect to document the dependency, or 
> even not notice it; or the second engineer could just fail to read the 
> documentation thoroughly enough.  There is 

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-15 Thread Kevin Nattinger via swift-evolution

> On Oct 14, 2017, at 7:54 PM, Xiaodi Wu  wrote:
> 
> On Sat, Oct 14, 2017 at 6:17 PM, Kevin Nattinger  > wrote:
>>> […]
>>> * A Swift `Sequence` is, to put it simplistically, a thing that can be 
>>> iterated over in a `for...in` loop. If it would make you happy, for the 
>>> rest of the discussion, let's suppose we called the protocol `ForLoopable` 
>>> instead of `Sequence`.
>> 
>> ForLoopable is so ugly. Since we’re just iterating over the elements, how 
>> about, oh, say, `Iterable`? Hey, that looks familiar.
>> 
>> I'm not trying to bikeshed the name of `Sequence`. I'm picking an 
>> intentionally unwieldy name for the purposes of discussing the semantics of 
>> this particular protocol. The point is that the underlying issue has nothing 
>> to do with the name; it can be `Iterable` or it can be `SpongeBob` for all I 
>> care.
> 
> I’m not trying to bikeshed the name either, The underlying issue is that 
> (what is currently) Sequence actually encompasses two separate 
> functionalities, and those functionalities need to be separated with their 
> separate semantic requirements documented. “Sequence: Iterable,” 
> “OrderedSequence: Sequence,” “SpongeBob: ForLoopable,” the names are 100% 
> irrelevant at this point; what’s important is that one is not necessarily 
> ordered and the other guarantees an order.
>  
> 
> What are the "two separate functionalities”?

Iteration, with convenience methods that don’t imply or rely on an order that 
may not be there; and convenience methods applicable to sequences that do have 
an intrinsic order.

> All the extension methods on Sequence are ways of spelling things that you 
> can write in a few lines of code using a `for...in` loop; they're in the 
> stdlib to allow a more functional style which some prefer. If you accept that 
> a type should support iteration with a `for...in` loop, then what is your 
> basis for claiming that these extension methods are "separate 
> functionalities”?

Just because you *can* express something in code doesn’t mean you should, or 
that it’s correct. It is objectively false to say a Set has a first or last 
object, because the objects therein have no order. You can take a random object 
from the set and call it “first”, but that doesn’t make that a correct 
definition of Set.first. A Set has no order, a specific iteration has an 
“order” only in the sense that all and only the objects in the set have to come 
out one at a time, but that doesn’t mean the Set itself has an order, 
specifically a first or last object.

You’re a fan of the principal of least surprise. Tell me, which would be less 
surprising: Set.dropFirst() actually drops a random element, or Set doesn’t 
have a dropFirst()? And if you think dropFirst() removing an element at random 
is not surprising, please explain why.

>>> […]
>> 
>>> * If a type `T` conforms to `ForLoopable` and an instance `t` of that type 
>>> has at least one element, then *something* has to be the first element in a 
>>> `for element in t { ... }` loop. Put another way, every instance of a type 
>>> that conforms to `ForLoopable` must have at least one publicly observable 
>>> order (although, intriguingly, I'm not sure it has to be a repeatable one). 
>>> It is possible, therefore, to have a semantic answer to the question of 
>>> which element is `first` or (if finite) `last`; one can also 
>>> `drop(while:)`, etc., and perform lexicographical comparisons.
>> 
>> As a side effect of Swift being a procedural language each iteration happens 
>> to occur in some order, yes, but that order is meaningless and reflects 
>> nothing about the Set itself.  In fact, I’d say that `first`, `last`, etc. 
>> are not even defined on the original Set per se, only on the specific order 
>> that a particular iteration resulted in. And that order is not necessarily 
>> predictable, nor necessarily stable, as you yourself said.
>> 
>> Consider an Iterable that gives a different order every time it’s iterated. 
>> Should calling `.first` or `last` give a different object every time?  
>> That’s absurd.
>> Should an object lexicographically compare not equal to itself? Even more 
>> absurd. 
>> 
>> What's your basis for saying that such behavior is absurd? It is explicitly 
>> permitted for instances of types conforming to `SpongeBob` to be single-pass 
>> and/or infinite. For a single-pass `SpongeBob`, `first` will certainly 
>> return a different value every time it is invoked.
> 
> Is `first` mutating? No. Should it be? No! `first` and `last` are a peek at 
> the state of the object.
> 
> You're right, `first` should not be mutating; that's actually an important 
> design consideration, as Ole pointed out, and it's not actually available on 
> `Sequence` for that reason. However, `first { _ in true }` is available and 
> is potentially mutating, as are all methods on Sequence by design.
> 
> Is `elementsEqual` (or *shudder* 

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-14 Thread Kevin Nattinger via swift-evolution
>> […]
>> * A Swift `Sequence` is, to put it simplistically, a thing that can be 
>> iterated over in a `for...in` loop. If it would make you happy, for the rest 
>> of the discussion, let's suppose we called the protocol `ForLoopable` 
>> instead of `Sequence`.
> 
> ForLoopable is so ugly. Since we’re just iterating over the elements, how 
> about, oh, say, `Iterable`? Hey, that looks familiar.
> 
> I'm not trying to bikeshed the name of `Sequence`. I'm picking an 
> intentionally unwieldy name for the purposes of discussing the semantics of 
> this particular protocol. The point is that the underlying issue has nothing 
> to do with the name; it can be `Iterable` or it can be `SpongeBob` for all I 
> care.

I’m not trying to bikeshed the name either, The underlying issue is that (what 
is currently) Sequence actually encompasses two separate functionalities, and 
those functionalities need to be separated with their separate semantic 
requirements documented. “Sequence: Iterable,” “OrderedSequence: Sequence,” 
“SpongeBob: ForLoopable,” the names are 100% irrelevant at this point; what’s 
important is that one is not necessarily ordered and the other guarantees an 
order.
 
>> […]
> 
>> * If a type `T` conforms to `ForLoopable` and an instance `t` of that type 
>> has at least one element, then *something* has to be the first element in a 
>> `for element in t { ... }` loop. Put another way, every instance of a type 
>> that conforms to `ForLoopable` must have at least one publicly observable 
>> order (although, intriguingly, I'm not sure it has to be a repeatable one). 
>> It is possible, therefore, to have a semantic answer to the question of 
>> which element is `first` or (if finite) `last`; one can also `drop(while:)`, 
>> etc., and perform lexicographical comparisons.
> 
> As a side effect of Swift being a procedural language each iteration happens 
> to occur in some order, yes, but that order is meaningless and reflects 
> nothing about the Set itself.  In fact, I’d say that `first`, `last`, etc. 
> are not even defined on the original Set per se, only on the specific order 
> that a particular iteration resulted in. And that order is not necessarily 
> predictable, nor necessarily stable, as you yourself said.
> 
> Consider an Iterable that gives a different order every time it’s iterated. 
> Should calling `.first` or `last` give a different object every time?  That’s 
> absurd.
> Should an object lexicographically compare not equal to itself? Even more 
> absurd. 
> 
> What's your basis for saying that such behavior is absurd? It is explicitly 
> permitted for instances of types conforming to `SpongeBob` to be single-pass 
> and/or infinite. For a single-pass `SpongeBob`, `first` will certainly return 
> a different value every time it is invoked.

Is `first` mutating? No. Should it be? No! `first` and `last` are a peek at the 
state of the object.
Is `elementsEqual` (or *shudder* lexicographicallyEqual) reflexive? IMO it 
clearly should be. Especially with the “lexicographically” part—from everything 
I can find, a lexicographical ordering is by definition reflexive. Do you have 
a citation for the idea that lexicographical equality can legitimately be 
non-reflexive?

> A random number generator fulfills all the semantic requirements of 
> conforming to `SpongeBob`, and in fact I do just that in NumericAnnex 
> . 
> `first` gives a different value every time, and a randomly generated 
> `SpongeBob` would unsurprisingly compare lexicographically not equal to 
> itself.

IMO that’s a bug in the implementation; lexicographical equality is reflexive, 
period.

Presumably the `elementsEqual` method contains something along these lines 
(take from SequenceAlgorithms.swift.gyb):

var iter1 = self.makeIterator()
var iter2 = other.makeIterator()

By creating two iterators, you’re mutating while iterating. Turns out there’s 
even a warning against this in Sequence.swift:

/// Using Multiple Iterators
/// 
///
/// Whenever you use multiple iterators (or `for`-`in` loops) over a single
/// sequence, be sure you know that the specific sequence supports repeated
/// iteration, either because you know its concrete type or because the
/// sequence is also constrained to the `Collection` protocol.
///
/// Obtain each separate iterator from separate calls to the sequence's
/// `makeIterator()` method rather than by copying. Copying an iterator is
/// safe, but advancing one copy of an iterator by calling its `next()` method
/// may invalidate other copies of that iterator. `for`-`in` loops are safe in
/// this regard.

The default implementation of elementsEqual is therefore unsafe because it has 
the potential for using an invalidated iterator.

> 
> On the other hand, if I have a collection of objects that I want iterated in 
> a particular order, I can use a container that iterates in a specific, known, 

[swift-evolution] Fwd: [Draft] Rename Sequence.elementsEqual

2017-10-14 Thread Kevin Nattinger via swift-evolution


> Begin forwarded message:
> 
> From: Kevin Nattinger 
> Subject: Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual
> Date: October 14, 2017 at 12:52:34 AM PDT
> To: Xiaodi Wu 
> 
>> […]
>> Regardless of the specific type of ordering, lexicographicallyEquals says to 
>> me that the objects should be sorted into lexicographical order and 
>> compared. Precisely the opposite of the proposal.
>> 
>> That is an interesting interpretation. I suppose anyone has the right to 
>> interpret anything in any way they please, but this seems a uniquely 
>> idiosyncratic interpretation. The total ordering is over the set of all 
>> sequences, and the comparison is between two sequences--note that the 
>> function name uses the singular ("equals") and makes no reference to the 
>> lexicography or ordering of elements. Likewise, dictionaries don't sort 
>> "hello" and "world" by comparing "ehllo" and "dlorw”.
> 
> Others have expressed the same interpretation as well. It’s most certainly 
> not “uniquely idiosyncratic.”
> As for the rest of this, perhaps it’s the late hour, but I don’t see your 
> point or the relevance to my argument. I didn’t say anything about sorting 
> individual elements, just that elements would be reordered so that both 
> sequences would be in lexicographical order.  Comparing unordered collections 
> according to their (nonexistent) order is nonsensical, so the only useful way 
> to compare them would be to impose an external order.
> 

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-14 Thread Kevin Nattinger via swift-evolution

> On Oct 13, 2017, at 8:28 PM, Xiaodi Wu  wrote:
> 
> 
> 
> On Fri, Oct 13, 2017 at 12:03 PM, Kevin Nattinger  > wrote:
>> On Oct 13, 2017, at 6:52 AM, Xiaodi Wu > > wrote:
>> 
>> You’re welcome to bikeshed the entire API surface area of sequences and 
>> collections, but you won’t be the first to explore this area. A number of us 
>> looked into this area in the past few years and did not reach a measurable 
>> improved result.
> 
> I don’t need or want to bikeshed the entire sequence and collection surface 
> area, I just want to fix one clear and GLARING issue:
> 
> A Set is NOT a sequence.
> 
> Note that this goes for dictionaries and any other unordered “sequences" as 
> well.
> 
> That was in an early draft of my original email, but I dropped it because I 
> was afraid people would just stop reading and dismiss the idea out-of-hand 
> without considering the problem or arguments. Apparently I should have at 
> least put it at the bottom, so sorry if the root issue was unclear.
> 
>> Sequences can be ordered or unordered,
> 
> You seem to be confusing the English word “sequence” with the (current) Swift 
> protocol “Sequence." A sequence is, by definition, ordered. Not enforcing 
> that in a protocol does not override the English language, and as this entire 
> thread demonstrates, causes issues further on down the line.
> 
> We are discussing the Swift protocol `Sequence`. It really doesn't matter at 
> all what the English word "sequence" means, and any difference between the 
> English word and the Swift term is emphatically *not* the root cause of the 
> issue. Here's why:
> 
> * A Swift `Sequence` is, to put it simplistically, a thing that can be 
> iterated over in a `for...in` loop. If it would make you happy, for the rest 
> of the discussion, let's suppose we called the protocol `ForLoopable` instead 
> of `Sequence`.

ForLoopable is so ugly. Since we’re just iterating over the elements, how 
about, oh, say, `Iterable`? Hey, that looks familiar.

> 
> * `Set` should conform to `ForLoopable`. (This I state as a premise; if you 
> disagree with the notion that we should be able to iterate over the elements 
> of an instance of `Set` with a `for...in loop`, then it's clearly a whole 
> other discussion and not a question of what the English word "sequence" 
> means.)

Obviously, `Set: Iterable`. I don’t think I’ve said anything to suggest you 
shouldn’t be able to iterate over unordered collections.

> 
> * If a type `T` conforms to `ForLoopable` and an instance `t` of that type 
> has at least one element, then *something* has to be the first element in a 
> `for element in t { ... }` loop. Put another way, every instance of a type 
> that conforms to `ForLoopable` must have at least one publicly observable 
> order (although, intriguingly, I'm not sure it has to be a repeatable one). 
> It is possible, therefore, to have a semantic answer to the question of which 
> element is `first` or (if finite) `last`; one can also `drop(while:)`, etc., 
> and perform lexicographical comparisons.

As a side effect of Swift being a procedural language each iteration happens to 
occur in some order, yes, but that order is meaningless and reflects nothing 
about the Set itself.  In fact, I’d say that `first`, `last`, etc. are not even 
defined on the original Set per se, only on the specific order that a 
particular iteration resulted in. And that order is not necessarily 
predictable, nor necessarily stable, as you yourself said.

Consider an Iterable that gives a different order every time it’s iterated. 
Should calling `.first` or `last` give a different object every time?  That’s 
absurd.
Should an object lexicographically compare not equal to itself? Even more 
absurd. 

On the other hand, if I have a collection of objects that I want iterated in a 
particular order, I can use a container that iterates in a specific, known, 
well-defined way, and use that to construct the sequence of objects.  That’s 
clearly an Iterable collection, but the guarantee is stronger than that. Since 
it iterates objects in a specific sequence, the logical way to express that 
would be `Sequence: Iterable`. Again, we’ve seen that before.  

Now, since a Sequence is guaranteed to iterate the same every time, suddenly 
our `first`, `last`, `drop*`, etc. methods have a meaning inherent to the 
collection itself, rather than a specific iteration. 
`first` is the first object in the Sequence. It doesn’t matter how the sequence 
came to be in that order; it doesn’t matter whether or not the sequence has 
already been iterated or how many times. `first` is the first object that is, 
was, and always will be presented by the Sequence’s Iterator. (Until the 
collection is mutated, obviously).

To summarize,
A Set has no intrinsic order. You can iterate over it, and a specific iteration 
of a set has an order, 

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-13 Thread Kevin Nattinger via swift-evolution
> 
> Is seems like you’re arguing we should attack the “Ordered versus unordered” 
> dichotomy prior to any name change. Is that correct?
> 

Yes, that's exactly my primary argument. 

(The secondary argument being that in either case the name should not be 
changed, at least not to the proposed one.)

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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-13 Thread Kevin Nattinger via swift-evolution

> On Oct 13, 2017, at 10:01 AM, Michael Ilseman <milse...@apple.com> wrote:
> 
> 
> 
>> On Oct 12, 2017, at 9:57 PM, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>> –∞
>> 
>> 1. I strongly object to the proposed name. It doesn't make it more clear to 
>> me what the method does, and is misleading at best. Among other issues, 
>> "lexicographical" is defined as alphabet order, and (1) this method applies 
>> to objects that are not Strings, and (2) this method's behavior isn't any 
>> more well-defined for Strings, so that name is even more of a lie than the 
>> original.
>> 
> 
> FWIW, in the context of String, "lexicographical ordering” does not imply 
> human-written-language-alphabetical order at all, as there’s no universal 
> alphabetical ordering for human language. I.e., such a concrete notion for 
> Strings does not exist, not even theoretically. “Lexicographical” derives its 
> meaning from the mathematical usage[1] which uses that term as well as 
> “alphabet” without being restricted to human-written-language, in which it 
> means some total ordering over a finite set.
> 
> [1] https://en.wikipedia.org/wiki/Lexicographical_order 
> <https://en.wikipedia.org/wiki/Lexicographical_order>
I see, apologies for the mistake. 
Regardless of the specific type of ordering, lexicographicallyEquals says to me 
that the objects should be sorted into lexicographical order and compared. 
Precisely the opposite of the proposal.

> 
>> 2. This is really just a symptom of a bigger problem. The fact that two Sets 
>> can compare equal and yet return different results for that method (among 
>> too many others) is logically inconsistent and points to a much deeper issue 
>> with Set and Sequence. It is probably about 3 releases too late to get this 
>> straightened out properly, but I'll outline the real issue in case someone 
>> has an idea for fixing it.
>> 
>> The root of the problem is that Set conforms to Sequence, but Sequence 
>> doesn't require a well-defined order. Since Set doesn't have a well-defined 
>> order, a significant portion of its interface is unspecified. The methods 
>> are implemented because they have to be, but they doesn't have well-defined 
>> or necessarily consistent results.
>> 
>> A sequence is, by definition, ordered. That is reflected in the fact that 
>> over half the methods in the main Sequence definition* make no sense and are 
>> not well-defined unless there is a well-defined order to the sequence 
>> itself. What does it even mean to `dropFirst()` in a Set? The fact that two 
>> objects that compare equal can give different results for a 100% 
>> deterministic function is illogical, nonsensical, and dangerous.
>> 
>> * 7/12 by my count, ignoring `_*` funcs but including the `var`
>> 
>> The current contents of Sequence can be cleanly divided into two groups; 
>> those that return SubSequence imply a specific ordering, and the rest do not.
>> 
>>  I think those should be/should have been two separate protocols:
>> 
>> public protocol Iterable {
>>   associatedtype Iterator: IteratorProtocol
>>   func map(...) -> [T] // Iterable where .Iterator.Element == T
>>   func filter(...) -> [Iterator.Element] // Iterable where .Iterator.Element 
>> == Self.Iterator.Element
>>   func forEach(...)
>>   func makeIterator() -> Iterator
>>   var underestimatedCount: Int { get }
>> }
>> 
>> public protocol Sequence: Iterable { // Maybe OrderedSequence just to make 
>> the well-defined-order requirement explicit
>>   associatedtype SubSequence
>>   func dropFirst(...)   -> SubSequence   // Sequence where .Iterator.Element 
>> == Self.Iterator.Element
>>   func dropLast(...)-> SubSequence   //" "
>>   func drop(while...)   -> SubSequence   //" "
>>   func prefix(...)  -> SubSequence   //" "
>>   func prefix(while...) -> SubSequence   //" "
>>   func suffix(...)  -> SubSequence   //" "
>>   func split(...where...)  -> [SubSequence] // Iterable where 
>> .Iterator.Element == (Sequence where .Iterator.Element == 
>> Self.Iterator.Element)
>> }
>> 
>> (The comments, of course, would be more sensible types once the ideas can 
>> actually be expressed in Swift)
>> 
>> Then unordered collections (Set and Dictionary) would just conform to 
>> Iterable and not Sequence, so ALL the methods on those classes would make 
>> logic

[swift-evolution] Fwd: [Draft] Rename Sequence.elementsEqual

2017-10-13 Thread Kevin Nattinger via swift-evolution

> On Oct 13, 2017, at 6:52 AM, Xiaodi Wu <xiaodi...@gmail.com 
> <mailto:xiaodi...@gmail.com>> wrote:
> 
> You’re welcome to bikeshed the entire API surface area of sequences and 
> collections, but you won’t be the first to explore this area. A number of us 
> looked into this area in the past few years and did not reach a measurable 
> improved result.

I don’t need or want to bikeshed the entire sequence and collection surface 
area, I just want to fix one clear and GLARING issue:

A Set is NOT a sequence.

Note that this goes for dictionaries and any other unordered “sequences" as 
well.

That was in an early draft of my original email, but I dropped it because I was 
afraid people would just stop reading and dismiss the idea out-of-hand without 
considering the problem or arguments. Apparently I should have at least put it 
at the bottom, so sorry if the root issue was unclear.

> Sequences can be ordered or unordered,

You seem to be confusing the English word “sequence” with the (current) Swift 
protocol “Sequence." A sequence is, by definition, ordered. Not enforcing that 
in a protocol does not override the English language, and as this entire thread 
demonstrates, causes issues further on down the line.

> single-pass or multi-pass, finite or infinite, lazy or eager. Not all the 
> combinations of these attributes make sense, but many do. For each 
> combination, a different subset of the sequence algorithms are “useful.” As 
> an example, “last” is not great for an infinite sequence.
> It’s possibly also not what you want for a single-pass sequence.

All of those actually are *sequences*, so it's essentially irrelevant to this 
discussion about not-sequences that conform to Sequence anyway.
 That said, because they are all sequences, there are still a few rational 
behaviors that make logical sense. An infinite loop or nil for infinite.last 
both make sense to me, and it IS what you want for a single-pass set, IMO it's 
a programmer error if the user calls last and they didn't want to burn the set.

> Now, as to the problem discussed here. It’s an orthogonal problem to what you 
> are discussing because, whether or not you reorganize the protocols entirely, 
> there is still going to be confusion about how exactly “elementsEqual” 
> differs from “==“ even for an ordered sequence. The name is clearly 
> problematic in that respect. However, I would argue that the behavior of the 
> method isn’t “improper” and the behavior is not “badly defined.”

Sure, `elementsEqual` isn't perfect, but it's a hell of a lot better than 
`lexicographicallyEquals`. And once you restrict Sequence to properly ordered 
sets, it makes a lot more sense. The problem is a function that compares 
elements "in the same order" when one or both of the sequences doesn't HAVE an 
order.


> 
> On Fri, Oct 13, 2017 at 07:09 Benjamin G <benjamin.garrig...@gmail.com 
> <mailto:benjamin.garrig...@gmail.com>> wrote:
>> +1 on both points. As for your solutions, i see 1/ as the best solution. 
>> Breaking source code that rely on badly defined, or improper behavior isn't 
>> "breaking".  You don't break something that's already half broken.
>> As an app developer relying on swift on my day to day job and making a 
>> living of it, i want to emphasis this: I really don't mind if a language 
>> version change is making me look more carefully on some parts of my code 
>> that i probably had overlooked. 
>> Sure i may pester a bit when the code doesn't compile, but it sure is better 
>> than discovering the weird behavior of a badly defined protocol hierarchy in 
>> customer support.
>> 
>> 
>> On Fri, Oct 13, 2017 at 6:57 AM, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> –∞
>> 
>> 1. I strongly object to the proposed name. It doesn't make it more clear to 
>> me what the method does, and is misleading at best. Among other issues, 
>> "lexicographical" is defined as alphabet order, and (1) this method applies 
>> to objects that are not Strings, and (2) this method's behavior isn't any 
>> more well-defined for Strings, so that name is even more of a lie than the 
>> original.
>> 
>> 2. This is really just a symptom of a bigger problem. The fact that two Sets 
>> can compare equal and yet return different results for that method (among 
>> too many others) is logically inconsistent and points to a much deeper issue 
>> with Set and Sequence. It is probably about 3 releases too late to get this 
>> straightened out properly, but I'll outline the real issue in case someone 
>> has an idea for fixing it.
>> 
>> The root of the problem is that Set c

Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-13 Thread Kevin Nattinger via swift-evolution

> 1. We could go ahead and make this separation. Although it's a potentially 
> large breaking change, I would argue that because the methods are ill-defined 
> anyway, the breakage is justified and a net benefit.
> 
> 2. We could try and think of a way to make the distinction between ordered 
> and unordered "sequences" in a less-breaking manner. Unfortunately, I don't 
> have a good suggestion for this, but if anyone has ideas, I'm all ears. Or 
> eyes, as the case may be.

It occurred to me, if we keep (and document) Sequence as unordered and move all 
the ordered methods to a new OrderedSequence, then we'd only be breaking truly 
broken code and we could even potentially offer a fix-it to change Sequence to 
OrderedSequence when we see the user using the ordered methods in places where 
we can see and change the generic definition. 

I think I'd still prefer Iterable/Sequence as far as naming, but this may be a 
more acceptable change, and I'd rather have this than no change. 


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


Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual

2017-10-12 Thread Kevin Nattinger via swift-evolution
–∞

1. I strongly object to the proposed name. It doesn't make it more clear to me 
what the method does, and is misleading at best. Among other issues, 
"lexicographical" is defined as alphabet order, and (1) this method applies to 
objects that are not Strings, and (2) this method's behavior isn't any more 
well-defined for Strings, so that name is even more of a lie than the original.

2. This is really just a symptom of a bigger problem. The fact that two Sets 
can compare equal and yet return different results for that method (among too 
many others) is logically inconsistent and points to a much deeper issue with 
Set and Sequence. It is probably about 3 releases too late to get this 
straightened out properly, but I'll outline the real issue in case someone has 
an idea for fixing it.

The root of the problem is that Set conforms to Sequence, but Sequence doesn't 
require a well-defined order. Since Set doesn't have a well-defined order, a 
significant portion of its interface is unspecified. The methods are 
implemented because they have to be, but they doesn't have well-defined or 
necessarily consistent results.

A sequence is, by definition, ordered. That is reflected in the fact that over 
half the methods in the main Sequence definition* make no sense and are not 
well-defined unless there is a well-defined order to the sequence itself. What 
does it even mean to `dropFirst()` in a Set? The fact that two objects that 
compare equal can give different results for a 100% deterministic function is 
illogical, nonsensical, and dangerous.

* 7/12 by my count, ignoring `_*` funcs but including the `var`

The current contents of Sequence can be cleanly divided into two groups; those 
that return SubSequence imply a specific ordering, and the rest do not.

 I think those should be/should have been two separate protocols:

public protocol Iterable {
  associatedtype Iterator: IteratorProtocol
  func map(...) -> [T] // Iterable where .Iterator.Element == T
  func filter(...) -> [Iterator.Element] // Iterable where .Iterator.Element == 
Self.Iterator.Element
  func forEach(...)
  func makeIterator() -> Iterator
  var underestimatedCount: Int { get }
}

public protocol Sequence: Iterable { // Maybe OrderedSequence just to make the 
well-defined-order requirement explicit
  associatedtype SubSequence
  func dropFirst(...)   -> SubSequence   // Sequence where .Iterator.Element == 
Self.Iterator.Element
  func dropLast(...)-> SubSequence   //" "
  func drop(while...)   -> SubSequence   //" "
  func prefix(...)  -> SubSequence   //" "
  func prefix(while...) -> SubSequence   //" "
  func suffix(...)  -> SubSequence   //" "
  func split(...where...)  -> [SubSequence] // Iterable where .Iterator.Element 
== (Sequence where .Iterator.Element == Self.Iterator.Element)
}

(The comments, of course, would be more sensible types once the ideas can 
actually be expressed in Swift)

Then unordered collections (Set and Dictionary) would just conform to Iterable 
and not Sequence, so ALL the methods on those classes would make logical sense 
and have well-defined behavior; no change would be needed for ordered 
collections.

Now, the practical matter. If this were Swift 1->2 or 2->3, I doubt there would 
be a significant issue with actually making this change. Unfortunately, we're 
well beyond that and making a change this deep is an enormous deal. So I see 
two ways forward.

1. We could go ahead and make this separation. Although it's a potentially 
large breaking change, I would argue that because the methods are ill-defined 
anyway, the breakage is justified and a net benefit.

2. We could try and think of a way to make the distinction between ordered and 
unordered "sequences" in a less-breaking manner. Unfortunately, I don't have a 
good suggestion for this, but if anyone has ideas, I'm all ears. Or eyes, as 
the case may be.


> On Oct 12, 2017, at 4:24 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> Rename Sequence.elementsEqual
> 
> Proposal: SE- 
> Authors: Xiaodi Wu 
> Review Manager: TBD
> Status: Awaiting review
>  
> Introduction
> 
> The current behavior of Sequence.elementsEqual is potentially confusing to 
> users given its name. Having surveyed the alternative solutions to this 
> problem, it is proposed that the method be renamed to 
> Sequence.lexicographicallyEquals.
> 
> [...]
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Random Unification

2017-10-12 Thread Kevin Nattinger via swift-evolution
> On Oct 12, 2017, at 6:13 AM, Jeremy Pereira  
> wrote:
> 
> 
> 
>> On 11 Oct 2017, at 18:01, Kevin Nattinger  wrote:
>> 
>> IMO, if we have the extensions on Int(eger)/Float(ingPoint)/Array 
>> (RandomAccessSequence?), they should just be for convenience and with a sane 
>> default RNG*, and users that need more should just use methods on the RNGs 
>> directly.
>> 
>> *: I don't think the default necessarily needs to be a CSRNG; if there's a 
>> fast one, fine. Are we building a padded room for the least competent 
>> engineer or a tool for the average to good engineer to use efficiently?
> 
> I don’t disagree that there should be a *default* RNG. I’m just pointing out 
> that there are advantages to being able to override the default, and Swift 
> has language features that allow you to do so without impacting the 
> simplicity of the default version. I do not understand why, if you are going 
> to have 
> 
>init(randomInRange: Countable{Closed}Range)
> 
> you would be against also having 
> 
>init(randomInRange: Countable{Closed}Range, ing: RNG)
> 
> as well. It’s both convenient and flexible.

My point is that the root method ("designated [not actually an] initializer") 
should be `rngInstance.randomInt()`, so I don't see a reason to also have an 
RNG argument on the convenience `Int.random()`.


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


Re: [swift-evolution] [Proposal] Random Unification

2017-10-11 Thread Kevin Nattinger via swift-evolution
IMO, if we have the extensions on Int(eger)/Float(ingPoint)/Array 
(RandomAccessSequence?), they should just be for convenience and with a sane 
default RNG*, and users that need more should just use methods on the RNGs 
directly.

*: I don't think the default necessarily needs to be a CSRNG; if there's a fast 
one, fine. Are we building a padded room for the least competent engineer or a 
tool for the average to good engineer to use efficiently?

> On Oct 11, 2017, at 9:08 AM, Jeremy Pereira via swift-evolution 
>  wrote:
> 
> I’m a bit late to the party on this one, but has anybody considered the fact 
> that you need a way for the user of the interface to override the default 
> random number source?
> 
> For example, some applications require a cryptographically secure source, 
> others might eschew perfect entropy for speed. Still others might want 
> repeatability e.g. Minecraft lets you enter a seed when it does the World 
> generation so you can go back and play the same World again and again. For 
> unit testing, you might want to replace the random number generator with a 
> sequence of hard coded values so you can exactly control the code path that 
> the test takes.
> 
> So if you have a protocol that describes an API for generating random numbers 
> called RNG, the extension on Int would look something like
> 
> extension Int {
>  init(randomInRange: Countable{Closed}Range, rng: RNG = /* a CS random 
> number generator */)
> }
> 
>> On 7 Oct 2017, at 04:24, Chris Lattner via swift-evolution 
>>  wrote:
>> 
>> 
>>> On Oct 5, 2017, at 10:58 AM, Nate Cook via swift-evolution 
>>>  wrote:
>>> 
>>> The edge case is really the same (empty ranges), it’s about what we do with 
>>> the edge case. If we include the methods on integer types, usage will look 
>>> like this:
>>> 
>>>let x = Int.random(in: 0..<5) // 3
>>>let y = Int.random(in: 0..<0) // runtime error
>>> 
>>> If we only have the collection methods, usage will look like this:
>>> 
>>>let x = (0..<5).random()! // 3
>>>let y = (0..<0).random()! // runtime error
>> 
>> These aren’t the forms I was suggesting, what I meant was:
>> 
>> extension Int {
>>  init(randomInRange: Countable{Closed}Range)
>> }
>> 
>> which gives:
>>  let x = Int(randomInRange: 0..<5)
>> 
>> The point of this is that you’re producing an Int (or whatever type).  
>> Regardless of whether the initializer is failable or not, this is the 
>> preferred way of creating a new value with some property: it is an 
>> initializer with a label.
>> 
>> -Chris
>> 
>> 
>> ___
>> 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] [Proposal] Random Unification

2017-09-08 Thread Kevin Nattinger via swift-evolution

> On Sep 8, 2017, at 2:46 PM, Jacob Williams via swift-evolution 
>  wrote:
> 
> What if we did it with something like this:
> 
> protocol RandomGenerator {
>   associated type T: Numeric // Since numeric types are the only kinds 
> where we could get a random number?
>   func uniform() -> T
>   // Other random type functions...
> }

I support a protocol, but not one with an associated type; those are an 
enormous pain in the rear to work with. They're quite probably my biggest gripe 
with Swift (and it's not a short list).  I shouldn't have to make an entire 
class generic just so I can have an RNG that I'll probably want to be a private 
field anyway.

> 
> Although if we didn’t constrain T to Numeric then collections could also 
> conform to it, although I’m not sure that collections would want to directly 
> conform to this. There may need to be a separate protocol for types with 
> Numeric indexes?
> 
> I’m no pro and really haven’t thought about this too deeply. Mostly just 
> spitballing/brainstorming.
> 
>> On Sep 8, 2017, at 3:03 PM, Jacob Williams via swift-evolution 
>> > wrote:
>> 
>> Huge +1 to stdlib (or even Foundation) random number generator. I’ve worked 
>> with random numbers on both Linux and macOS/iOS and have found myself 
>> annoyed with the lack of easy random number generators. It seems that 
>> implementing a pure Swift RNG would be an obviously good addition to the 
>> stdlib.
>> 
>> I don’t think that it would be possible to make this work for floating point 
>> numbers. Although admittedly, I know very little about Floating Point 
>> numbers. I think this is still a worthwhile addition to Swift even for just 
>> Integers alone.
>> 
>>> On Sep 8, 2017, at 1:30 PM, Ben Cohen via swift-evolution 
>>> > wrote:
>>> 
>>> Hi Alejandro,
>>> 
>>> I’m really happy to see someone pick this up. We had suggested some kind of 
>>> random support could be a goal for addition to the standard library in 
>>> Swift 4 phase 2 but didn’t manage it, so I definitely think a good proposal 
>>> would be given consideration for Swift 5.
>>> 
>>> Regarding the implementation – I would suggest exploring something along 
>>> the lines of an extension on RandomAccessCollection that adds a property 
>>> for a random element, rather than a pair of free functions. This would have 
>>> a number of benefits:
>>> 
>>>  - a very common use case is picking a random entry from a collection, 
>>> which this would do automatically
>>>  - it gives you a very natural way of expressing a ranged random number 
>>> i.e. (0..<10).randomElement (not necessarily recommending that name btw, 
>>> it’s one of various possibilities)
>>>  - since both kinds of countable ranges are collections, it sidesteps that 
>>> issue :)
>>>  - it allows for multiple different integers without the need for casting 
>>> i.e. in the above, if type context meant the result was a UInt16, that’s 
>>> what it would be
>>> 
>>> The one downside is that you’d have to write (0..>> justification for a static property on one of the Integer protocols as 
>>> shorthand for that.
>>> 
>>> The tricky part (in addition to the cross-platform aspect) is ensuring 
>>> correct distribution across the possible distances. But since this is 
>>> something that people might easily get wrong, that reinforces the idea of 
>>> this being something that’s easy to use correctly in the std lib.
>>> 
>>> I’d also suggest proposing a shuffle implementation for 
>>> RandomAccessCollection+MutableCollection at the same time (probably as a 
>>> separate but linked proposal), since this is also something that is often 
>>> requested, easy to get wrong, and needs a cross-platform source of random 
>>> numbers.
>>> 
>>> Regards,
>>> Ben
>>> 
>>> 
 On Sep 8, 2017, at 10:34 AM, Alejandro Alonso via swift-evolution 
 > wrote:
 
 Range support is something that came up, and I think it’s a great idea as 
 well. My question now is do we support both `CountableRange` and 
 `CountableClosedRange`?
 
 On Sep 8, 2017, 12:08 PM -0500, Shawn Erickson >, wrote:
> It would be nice to leverage range support instead of a start and end 
> value IMHO.
> On Fri, Sep 8, 2017 at 9:52 AM Alejandro Alonso via swift-evolution 
> > wrote:
> Hello swift evolution, I would like to propose a unified approach to 
> `random()` in Swift. I have a simple implementation here 
> https://gist.github.com/Azoy/5d294148c8b97d20b96ee64f434bb4f5 
> . This 
> implementation is a simple wrapper over existing random functions so 
> 

Re: [swift-evolution] [Pitch] Synthesized static enum property to iterate over cases

2017-09-08 Thread Kevin Nattinger via swift-evolution
I've been waiting for this for years. Literally since Swift was announced. IMO 
it's one of several major gaps in the language.

Some thoughts:
- It should be a simple array. 
- By far the most simple solution, and the one I (and, I'd guess, 
others) would expect.
- Every time I've needed the count, I need the actual values either 
within the same method or within the same run loop (e.g. table view).
- In my experience, direct indexing into the values array is more 
common than iterating over it.
- Rarely more than a few cases.
- Even an enum with a lot of cases, the actual number is trivial 
compared to the program's memory usage.
- No compiler magic beyond spitting out the static array. How do you 
propose to generate on-demand a sequence of values without compiler magic and 
without the values being stored somewhere?
- It should always be in declaration order. Period. 
- Reordering only in the case of Int raw values (especially only when 
0-N are all covered) is unintuitive at best, and I expect rarely what the dev 
would want.
- Should only work on enums without associated values. Enumerating on 
associated values is just begging for trouble. 
- (Infinite) recursion, as you pointed out.
- It seems more intuitive to me to have enumerated cases grouped, but 
what if there are cases with and without ATs?

>> [...]
>> Great points! I was only considering the table view/section case where the 
>> enum had raw values 0..> could just define `enum Section { case header, content, footer }` and then 
>> want to turn an IndexPath value into the appropriate Section.
>> 
>> On the other hand, though, isn't that what raw value enums are for? If the 
>> user needs to do what you're saying—map specific integers to enum 
>> values—shouldn't they do so by giving those cases raw values and calling 
>> init?(rawValue:), not by indexing into a collection? Especially since they 
>> can already do that today, and the only thing they're missing is being able 
>> to retrieve the count, which a "PrecountedSequence" mentioned above, or 
>> something like it, could also provide.

I... guess one could do that? Seems undesirable to me. What if I have them 
explicitly numbered, and delete one? Oops, now the whole thing is off and I 
have to go fix all the numbers. Besides, what if the dev wants to use it as a 
different raw representable? (`enum Title: String { ... }`)?

> 
> First, I’m making observations about what people are doing, not what they 
> could do.  
> 
> Second, the raw value may not correspond to 0-based indices.  It might not 
> even be an Int.  There is no reason to couple this common use case of 
> `allValues` to `Int` raw values with 0-based indices.

+1000. There is absolutely no reason to join these, or special-case 0-N int raw 
representables. 

> 
> Do we know of any examples where a user is both (1) defining an enum with 
> integer raw values that are noncontiguous or non-zero-based and (2) need 
> declaration-ordinal-based indexing into those cases for other reasons, like a 
> table/collection view? I can't think of why someone would do that, but I'm 
> happy to consider something that I'm missing.

Some underlying meaning? E.g. not a table view, but values or identifiers for 
some sort of low-level protocol.

>  
> 
> Third, `init(rawValue:)` is a failable initializer and would require a force 
> unwrap.  If the raw values *are* 0-based integers this is similar to the 
> collection bounds check that would be necessary, but it moves it into user 
> code.  People don’t like writing force unwraps.
> 
> Yeah, this is a really good point that I wasn't fully considering. If other 
> invariants in the application hold—such as table view cell functions never 
> receiving a section index outside 0.. users to address a situation that will never actually occur unless UIKit is 
> fundamentally broken.

Or the user makes a mistake numbering cases, or forgets to update something, 
... I usually put an assertion failure there, but I hate relying on even system 
libraries in production code. 

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


Re: [swift-evolution] [Proposal] Random Unification

2017-09-08 Thread Kevin Nattinger via swift-evolution
IMO, we should have a `Random` or `RandomGenerator` interface and the stdlib 
can provide a `SystemRandom` that wraps arc4*/random(), and maybe a 
cryptographically secure one too (MT19937?).

protocol RandomGenerator {
func uniform() -> Int
func uniform() -> Double
func uniformBytes(count: Int) -> Data
}

Then we could add things like, e.g. a protocol extension to generate normally 
distributed numbers (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform 
).

extension RandomGenerator {
func normal() -> (T, T) {
// ...
}
}

> On Sep 8, 2017, at 10:08 AM, Shawn Erickson via swift-evolution 
>  wrote:
> 
> It would be nice to leverage range support instead of a start and end value 
> IMHO.
> On Fri, Sep 8, 2017 at 9:52 AM Alejandro Alonso via swift-evolution 
> > wrote:
> Hello swift evolution, I would like to propose a unified approach to 
> `random()` in Swift. I have a simple implementation here 
> https://gist.github.com/Azoy/5d294148c8b97d20b96ee64f434bb4f5 
> . This 
> implementation is a simple wrapper over existing random functions so existing 
> code bases will not be affected. Also, this approach introduces a new random 
> feature for Linux users that give them access to upper bounds, as well as a 
> lower bound for both Glibc and Darwin users. This change would be implemented 
> within Foundation.
> 
> I believe this simple change could have a very positive impact on new 
> developers learning Swift and experienced developers being able to write 
> single random declarations.
> 
> I’d like to hear about your ideas on this proposal, or any implementation 
> changes if need be.
> 
> - Alejando
> 
> ___
> 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] Introducing synthesized locks

2017-06-13 Thread Kevin Nattinger via swift-evolution
I'd prefer to see block-scoped synchronization rather than whole-method-only; 
it gives much more flexibility.

Note that you can use the objc synchronization feature with reference types:

// Or (_ obj:...) if you prefer the label-less objc style)
func synchronized(on obj: AnyObject, do block: () throws -> Void) rethrows {
objc_sync_enter(obj)
defer {
objc_sync_exit(obj)
}
try block()
}

// or synchronized(self)
synchronized(on: self) {
// do something
}
try synchronized(on: self) {
throw NSError()
}

Not 100% sure this works with bridged reference types (e.g. Array); definitely 
doesn't work with Int. Use a dummy NSObject() if needed.

That said, I'd love to see a swift-native solution that works with value types 
(and doesn't rely on the objc runtime).

> On Jun 12, 2017, at 2:10 AM, Erik Aigner via swift-evolution 
>  wrote:
> [...]
> With synchronized attribute (the semaphore/wait/deferred-signal is 
> synthesized by Swift automatically)
> 
> class Obj {
> 
>   synchronized func method() {
>   // semaphore is synthesized automatically, do something…
>   }
> }
> 

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


Re: [swift-evolution] Proposal: Allow #if to guard switch case clauses

2017-05-10 Thread Kevin Nattinger via swift-evolution
I support this proposal 100%. In fact, I just ran into this use case. 

I’d support extending it to allow partial-case coverage (as long as it doesn’t 
cross a case: boundary, obviously), e.g.

switch result {
case .success(let object):
doSomething(with: object)
case .error(let error):
#if debug
alertUser(error)
#endif
handleError(error)
}

I don’t see a reason to prevent that, but if we can just get the current 
proposal (full cases only) in Swift 4 I’ll be satisfied and just put this on my 
(large and growing) list of things to bring up for 5.

> On May 10, 2017, at 6:28 AM, rintaro ishizaki via swift-evolution 
>  wrote:
> 
> Here's proposal link:
> https://github.com/rintaro/swift-evolution/blob/conditional-switch-case/proposals/-conditional-switch-case.md
>  
> 
> 
> Fixed some typos, including my name :)
> 
> 2017-05-10 17:32 GMT+09:00 rintaro ishizaki  >:
> Hi evolution community,
> 
> This proposal allows you to enclose switch cases with #if directive.
> Implementation: https://github.com/apple/swift/pull/9457 
> 
> This is one of the oldest SR issue:
> https://bugs.swift.org/browse/SR-2 
> https://bugs.swift.org/browse/SR-4196 
> 
> Thanks!
> Rintaro
> 
> 
> Allow #if to guard switch case clauses
> 
> Proposal: SE- 
> Authors: Rintaro Ishziaki 
> Review Manager: TBD
> Status: Awaiting review
>  
> Introduction
> 
> This proposal adds ability to guard switch case clauses with #if directives.
> 
> Swift-evolution thread: Not yet 
> 
>  
> Motivation
> 
> When you want to switch cases only for certain compilation condition, say 
> switching #if os(Linux) guarded enum cases, right now you have to write 
> switch twice:
> 
> enum Operation {
>   case output(String)
> #if os(Linux)
>   case syscall(Syscall)
> #endif
> }
> 
> func execute(operation: Operation) {
> #if !os(Linux)
>switch operation {
>case .output(let str):
>print(str)
>}
> #else
>switch operation {
>case .output(let str):
>print(str)
>case .syscall(let call):
>call.execute()
>}
> #endif
> }
> This is annoying and error prone.
> 
>  
> Proposed
>  solution
> 
> This proposal allows #if to guard switch case clauses.
> 
> func execute(operation: Operation) {
> switch operation {
> case .output(let str):
> print(str)
> #if os(Linux)
> case .syscall(let call):
> call.execute()
> #endif
> }
> }
>  
> Detailed
>  design
> 
> This change shouldn't affect existing #if directives within case clauses. 
> This code should works as expected:
> 
> func foo(x: MyEnum) {
> switch x {
> case .some(let str):
> doSomething(str)
> #if PRINT_SOME
> print(str)
> #endif
> case .other:
> doOther()
> }
> }
> Only if the next token after #if is case or default, the Parser treat it as 
> guarding case clauses.
> 
> func foo(x: MyEnum) {
> switch x {
> case .some(let str):
> doSomething(str)
> #if HAS_OTHER
> case .other:
> doOther()
> }
> #endif
> }
> func foo(x: MyEnum) {
> switch x {
> case .some(let str):
> doSomething(str)
> #if HAS_OTHER
> default:
> break
> #endif
> }
> Error cases:
> 
> switch x {
> case .some(let str):
> doSomething(str)
> #if HAS_OTHER
> case .other:
> doOther()
> #else
> doMore() // error: all statements inside a switch must be covered by 
> a 'case' or 'default'
> #endif
> }
> switch x {
> case .some(let str):
> doSomething(str)
> #if HAS_OTHER
> doMore()
> case .other:
> doOther() // error: 'case' label can only appear inside a 'switch' 
> statement
> #else
> }
> You can guard multiple cases as long as it is guarding whole clauses:
> 
> switch x {
> case .some(let str):
> doSomething(str)
> #if HAS_OTHERS
> case .other:
> doOther()
> case .more:
> doMore()
> #else
> }
> 
>  
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Enum with generic cases

2017-04-24 Thread Kevin Nattinger via swift-evolution

> On Apr 24, 2017, at 3:16 PM, Jaden Geller  wrote:
> 
> 
>> On Apr 24, 2017, at 2:38 PM, Kevin Nattinger > > wrote:
>> 
>>> 
>>> How can I improve your understanding?
>>> 
>> 
>> 
>> Given the enum I was using earlier:
>> 
>> enum Thing {
>> case thingOne(T)
>> case thingTwo(T)
>> }
>> 
>> - Write a function that takes a thingOne or thingTwo but 
>> nothing else.
> 
> This isn’t possible since generic types introduced on cases are erased in the 
> type of `Thing`.
> 
> We can actually already achieve what you want by moving the generics onto the 
> type itself, and this is already possible in Swift! No new features are 
> necessary.
> 
> ```
> enum Thing {
> case thingOne(T1)
> case thingTwo(T2)
> }
> 
> func test(_ x: Thing) {
> switch x {
> case .thingOne(let s):
> print("The string has value \(s)!")
> case .thingTwo(let i):
> print("The int has value \(i)!")
> }
> }
> ```

Yes, that was almost exactly my original example. My understanding of the 
proposal is that it will remove that capability, which I find completely 
unacceptable.

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


Re: [swift-evolution] [Pitch] Enum with generic cases

2017-04-24 Thread Kevin Nattinger via swift-evolution
> 
> How can I improve your understanding?
> 


Given the enum I was using earlier:

enum Thing {
case thingOne(T)
case thingTwo(T)
}

- Write a function that takes a thingOne or thingTwo but nothing 
else.
- Declare a variable that can hold a thingOne or thingTwo but 
nothing else.

Or explain why something that is widely used, trivial to write, and necessary 
for type safety should be removed from the language.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Enum with generic cases

2017-04-24 Thread Kevin Nattinger via swift-evolution

> On Apr 24, 2017, at 1:36 PM, Jaden Geller <jaden.gel...@gmail.com> wrote:
> 
>> 
>> On Apr 24, 2017, at 1:15 PM, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>> This makes it more convenient to create them, sure, but how would you pass 
>> them around or extract the value in a type-safe manner?
> 
> If the case introduces a generic type, than the switching over that case 
> introduces a generic type variable in that scope.

I don’t want a generic type, I want to be able to specify exactly what types 
the function accepts. 

> 
>> 
>> e.g. now I can write:
>> enum Thing<T, U> {
>> case thingOne(T)
>> case thingTwo(U)
>> }
>> 
>> // How do I require thingOne or thingTwo?
>> func handle(thing: Thing<String, Int>) {
>> switch thing {
>> case .thingOne(let s): print("string \(s)")
>> case .thingTwo(let i): print("int \(i)")
>> }
>> }
>> 
>> With your proposed syntax:
>> 
>> enum Thing {
>> case thingOne(T)
>> case thingTwo(T)
>> }
>> 
>> func handle(thing: Thing) {
>> switch thing {
>> case thingOne(let s):
>> // What is the type of s?
> 
> It is some new generic variable `T`. It might be best to require that it is 
> explicitly introduced:
> ```
> case thingOne(let s):
> ```
> You could use `s` like you could use `x` in `func (x: T) { … }`. That’s to 
> say that you couldn’t do much with it. You could store it in an `Any`. You 
> could dynamically check the type. You could ignore it. You could print it.

So what good is a value I can’t do anything with?

> 
> It becomes a lot more useful when there are constraints on `T` in the 
> original case definition of the type. For example, if `case thingOne FloatingPoint>(T)` were written in the original enum definition, you could do 
> anything with `s` that you could do with a `FloatingPoint`.
> 
>> case thingTwo(let i):
>> // is it even possible to write an exhaustive switch?
> 
> Sure, but this switch isn’t yet exhaustive. You’d also have to add another 
> case:
> ```
> case thingTwo(let i):
> ```

In my original code, the function specifies exactly what it can handle, and 
that restriction is enforced by the compiler. Do you really think it would be 
an improvement to remove compile-time type restrictions? We may as well get rid 
of the type system and duck-type like python. At least that would speed up 
type-inference bottlenecks.

> When we do come back to this proposal, it might be reasonable to leave these 
> sorts of specializations (e.g. `case thingTwo`) out of the initial 
> design since they might significantly complicate the model and they are 
> entirely additive. I’m not sure though, I’m not familiar with the 
> implementation.
> 
>> }
>> }
>> 
> 
> I’d really love to see GADTs in Swift, even if in a more limited form! 
> Another GADT feature that would be nice to add (though probably would deserve 
> a separate, later proposal) would be specialized generic return types for 
> each case:
> 
> ```
> enum Expr {
> case value(T) -> Expr
> case plus(Expr, Expr) -> Expr
> case and(Expr, Expr) -> Expr
> case equals(Expr, Expr) -> Expr where T: Equatable
> }
> ```
> 
> But ya, I realize this is a very major complication of the model… Would be so 
> cool though!
> 
> This is all definitely out of scope for Swift 4, and likely out of scope for 
> Swift 5 even… I guess we’ll find out once we get there. Still fun to think 
> about!
> 
> Cheers,
> Jaden Geller
> 
>> 
>> 
>>> On Apr 24, 2017, at 6:57 AM, Joshua Alvarado via swift-evolution 
>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> Here is my pitch on adding generics to enum cases and not to the enum type 
>>> itself. Let me know if you have an improvements or modifications lets open 
>>> it to discussion thank you swiftys! :)
>>> 
>>> Enum with generic cases
>>> 
>>> Proposal: SE- 
>>> <https://github.com/lostatseajoshua/swift-evolution/blob/master/-enum-generic-cases.md>
>>> Authors: Joshua Alvarado <https://github.com/alvaradojoshua0>
>>> Review Manager: TBD
>>> Status: PITCH
>>> During the review process, add the following fields as needed:
>>> 
>>> Decision Notes: Rationale 
>>> <https://lists.swift.org/pipermail/swift-evolution/>, Additional Commen

Re: [swift-evolution] [Pitch] Enum with generic cases

2017-04-24 Thread Kevin Nattinger via swift-evolution

> On Apr 24, 2017, at 1:34 PM, Joshua Alvarado  
> wrote:
> 
> Well in your case thing one and thing two will be the same type as you are 
> using the same T generic type on both.

It’s two different and unrelated generics unless you’re intending to change the 
way generics work entirely.

func foo(x: T)
func bar(x: T)
They both use “T” as the generic, but the T’s are unrelated.  

You can even have a generic function type shadow the containing class’s generic 
type:

enum Thing {
case thingOne(T)
case thingTwo(U)

func foo(x: T) -> T { return x }
}

let x = Thing.thingOne("").foo(x: [5.0])
type(of: x) // Array.Type 

(Not recommended, obviously, just demonstrating that generic types are 
independent regardless of the name)

> 
> To achieve your case you can do an extension on the enum and use two 
> different generics:
> 
> enum Thing {
> case thingOne(T)
> case thingTwo(U)
> }
> 
> extension Thing where T == String, U == Int {

Ah, but there is no T or U on the enum, just on the cases. And what if the 
function needs to be in another class for encapsulation reasons? 
Furthermore, how would you even call this function? How do you create a 
variable that can hold either a thingOne with a string or a thingTwo with an 
Int, and nothing else?

>func handle(thing: Thing) {
> switch thing {
> case thingOne(let s):
> // s is type String
> 
> case thingTwo(let i):
> // i is an Int
> }
>}
> }
> 
> This can actually be achieved in Swift 3.1, you can run this in a playground.
> 
> enum Foo {
> case bar(obj: T)
> case baz(obj: U)
> 
> func handle() {
> switch self {
> case .bar(obj: let x):
> break
> case .baz(obj: let y):
> break
> }
> }
> }
> 
> extension Foo where T == String, U == Int {
> func handle() {
> switch self {
> case .bar(obj: let str):
> print(str)
> case .baz(obj: let aNum):
> print(aNum)
> }
> }
> }
> 
> let foo = Foo.baz(obj: 1)
> foo.handle() // prints 1
> 
> 
> 
> On Mon, Apr 24, 2017 at 2:15 PM, Kevin Nattinger  > wrote:
> This makes it more convenient to create them, sure, but how would you pass 
> them around or extract the value in a type-safe manner?
> 
> e.g. now I can write:
> enum Thing {
> case thingOne(T)
> case thingTwo(U)
> }
> 
> // How do I require thingOne or thingTwo?
> func handle(thing: Thing) {
> switch thing {
> case .thingOne(let s): print("string \(s)")
> case .thingTwo(let i): print("int \(i)")
> }
> }
> 
> With your proposed syntax:
> 
> enum Thing {
> case thingOne(T)
> case thingTwo(T)
> }
> 
> func handle(thing: Thing) {
> switch thing {
> case thingOne(let s):
> // What is the type of s?
> case thingTwo(let i):
> // is it even possible to write an exhaustive switch?
> }
> }
> 
> 
> 
>> On Apr 24, 2017, at 6:57 AM, Joshua Alvarado via swift-evolution 
>> > wrote:
>> 
>> Here is my pitch on adding generics to enum cases and not to the enum type 
>> itself. Let me know if you have an improvements or modifications lets open 
>> it to discussion thank you swiftys! :)
>> 
>> Enum with generic cases
>> 
>> Proposal: SE- 
>> 
>> Authors: Joshua Alvarado 
>> Review Manager: TBD
>> Status: PITCH
>> During the review process, add the following fields as needed:
>> 
>> Decision Notes: Rationale 
>> , Additional Commentary 
>> 
>> Bugs: SR- , SR- 
>> 
>> Previous Revision: 1 
>> 
>> Previous Proposal: SE- 
>> 
>>  
>> Introduction
>> 
>> This proposal adds a change to the enumeration type that allows an enum case 
>> to cast a generic on its associated value.
>> 
>> Swift-evolution thread: Discussion thread topic for that proposal 
>> 
>>  
>> Motivation
>> 
>> Enums currently support generics, but they are added onto the type itself. 
>> This can cause adverse syntax when implementing generics for associated 
>> values to be stored along each case. The enum case holds the associated 
>> value (not the enum type itself) so should create 

Re: [swift-evolution] [Pitch] Enum with generic cases

2017-04-24 Thread Kevin Nattinger via swift-evolution
This makes it more convenient to create them, sure, but how would you pass them 
around or extract the value in a type-safe manner?

e.g. now I can write:
enum Thing {
case thingOne(T)
case thingTwo(U)
}

// How do I require thingOne or thingTwo?
func handle(thing: Thing) {
switch thing {
case .thingOne(let s): print("string \(s)")
case .thingTwo(let i): print("int \(i)")
}
}

With your proposed syntax:

enum Thing {
case thingOne(T)
case thingTwo(T)
}

func handle(thing: Thing) {
switch thing {
case thingOne(let s):
// What is the type of s?
case thingTwo(let i):
// is it even possible to write an exhaustive switch?
}
}



> On Apr 24, 2017, at 6:57 AM, Joshua Alvarado via swift-evolution 
>  wrote:
> 
> Here is my pitch on adding generics to enum cases and not to the enum type 
> itself. Let me know if you have an improvements or modifications lets open it 
> to discussion thank you swiftys! :)
> 
> Enum with generic cases
> 
> Proposal: SE- 
> 
> Authors: Joshua Alvarado 
> Review Manager: TBD
> Status: PITCH
> During the review process, add the following fields as needed:
> 
> Decision Notes: Rationale 
> , Additional Commentary 
> 
> Bugs: SR- , SR- 
> 
> Previous Revision: 1 
> 
> Previous Proposal: SE- 
> 
>  
> Introduction
> 
> This proposal adds a change to the enumeration type that allows an enum case 
> to cast a generic on its associated value.
> 
> Swift-evolution thread: Discussion thread topic for that proposal 
> 
>  
> Motivation
> 
> Enums currently support generics, but they are added onto the type itself. 
> This can cause adverse syntax when implementing generics for associated 
> values to be stored along each case. The enum case holds the associated value 
> (not the enum type itself) so should create its own value constraints.
> 
>  
> Proposed
>  solution
> 
> The generic is to be casted on the case of the enum and not on the enum 
> itself.
> 
>  
> Detailed
>  design
> 
> Current implementation:
> 
> // enum with two generic types
> enum Foo {
> case bar(obj: T)
> case baz(obj: U)
> }
> 
> // U is to be casted but it is not even used
> let foo: Foo = .bar(obj: "hash")
> 
> // Creating an optional enum, the generics have to be casted without a value 
> set
> // The casting is really not needed as the values should be casted not the 
> enum
> var foo1: Foo?
> 
> // Collections don’t look great either
> var foos = [Foo]()
> foos.append(.bar(obj:"hash"))
> Proposed solution
> 
> enum Foo {
> case bar(obj: T)
> case baz(obj: U)
> }
> 
> // generic type inferred on T
> var foo: Foo = .bar(obj: "hash") 
> 
> // doesn’t need to cast the generic on the optional enum
> // the associated value will hold the cast
> var foo1: Foo? 
> 
> // This also gives better syntax with collections of enums with associated 
> types
> var foos = [Foo]()
> foos.append(.bar(obj: "hey")
>  
> Source
>  compatibility
> 
> This may cause subtle breaking changes for areas in code with generic enum 
> cases. The compiler could help with the change by finding the associated 
> generic and updating the case with the new syntax.
> 
>  
> Alternatives
>  considered
> 
> An alternative would be to extend the associatedtype keyword to the enum type.
> 
> enum Foo {
> associatedtype T = Hashable
> case bar(obj: T)
> }
> 
> Copy of proposal can be found here Swift proposal on github 
> 
> 
> -- 
> Joshua Alvarado
> alvaradojosh...@gmail.com 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

___
swift-evolution mailing list

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

2017-04-19 Thread Kevin Nattinger via swift-evolution
I agree, but unfortunately it’s probably too late now.

> On Apr 19, 2017, at 3:11 PM, Martin Waitz via swift-evolution 
>  wrote:
> 
> Hi,
> 
> I think, it would be more natural to include the last newline.
> Multi-line String literals are for multiple lines.
> And each line ends in a \n. Otherwise it wouldn’t be a line.
> 
> Having
> """
> line 1
> """
> +
> """
> line 2
> """
> ==
> """
> line 1
> line 2
> """
> 
> makes a lot of sense to me.
> 
> Or do we want to magically add a trailing newline everywhere as we do in 
> print()?
> Better change print to only add the newline when necessary! (e.g. by adding a 
> new parameter which defaults to „auto“)
> 
> — 
> Martin
> 
>> Am 19.04.2017 um 23:51 schrieb Adrian Zubarev via swift-evolution 
>> >:
>> 
>> This is the natural way of text blocks. If you really need a blank line you 
>> can add one at the start/end or alternatively use \n.
>> 
>> """
>> 
>> Foo  
>> 
>> """
>> 
>> // Equals "\nFoo\n"
>> 
>> 
>> 
>> -- 
>> Adrian Zubarev
>> Sent with Airmail
>> 
>> Am 19. April 2017 um 22:53:07, Vladimir.S via swift-evolution 
>> (swift-evolution@swift.org ) schrieb:
>> 
>>> On 19.04.2017 23:03, Joe Groff via swift-evolution wrote:
>>> > Proposal Link: 
>>> > https://github.com/apple/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>>> >  
>>> > 
>>> > 
>>> > Hello Swift Community,
>>> > 
>>> > The review of SE-0168: "Multi-Line String Literals" ran from April 
>>> > 6...12, 2017. The 
>>> > proposal is *accepted with revisions. *Community feedback was largely 
>>> > positive on the 
>>> > idea, though the discussion highlighted several under-specified aspects.
>>> > 
>>> > - Questions arose about whether text could appear on the same line as the 
>>> > opening and 
>>> > closing delimiter, and how that would interact with the de-indentation 
>>> > algorithm. The 
>>> > core team feels that it is important to keep this feature focused on its 
>>> > purpose of 
>>> > allowing the easy embedding of pasted blocks of text, so *text inside the 
>>> > literal on 
>>> > the same line as either delimiter should be disallowed.*
>>> > 
>>> > // Allowed, equal to "foo\nbar"
>>> > """
>>> > foo
>>> > bar
>>> > """
>>> 
>>> Could you clarify, shouldn't this be equal to "foo\nbar\n" ? I.e. with 
>>> trailing \n 
>>> for "bar" line?
>>> I didn't find any clarification about the injecting of line-end for last 
>>> text 
>>> line(not for the """ delimiter).
>>> 
>>> > 
>>> > // Not allowed
>>> > """foo
>>> > bar
>>> > """
>>> > 
>>> > // Not allowed
>>> > """
>>> > foo
>>> > bar"""
>>> > 
>>> > This keeps the model straightforward to describe: a *single newline *is 
>>> > always 
>>> > stripped after the opening delimiter and before the closing one, and the 
>>> > closing 
>>> > delimiter's position always determines the indentation level of the 
>>> > entire literal. 
>>> > The core team acknowledges that single-line triple quoted strings have 
>>> > other uses in 
>>> > other languages, such as to avoid excessive escaping in a string that 
>>> > contains lots 
>>> > of literal quotes, but supporting that alongside the 
>>> > indentation-stripping behavior 
>>> > leads to a lot of subtlety, and there could be other solutions to the 
>>> > escaping 
>>> > problem down the line, such as raw strings. If nothing else, single-line 
>>> > triple 
>>> > quoted strings can be considered later as an additive feature.
>>> > 
>>> > - The core team also believes that *underindentation or inconsistent 
>>> > tab/space usage 
>>> > within the indentation should be an error.* Every line inside the literal 
>>> > must begin 
>>> > with the exact sequence of spaces and tabs that precedes the closing 
>>> > delimiter.
>>> > 
>>> > """
>>> > this is OK
>>> > this is an error
>>> > this is also an error
>>> > under-indenting is an error too
>>> > but you can go nuts after the indentation all you want
>>> > you do you
>>> > """
>>> > 
>>> > - The quoted string should *normalize newlines* to \n in the value of the 
>>> > literal, 
>>> > regardless of whether the source file uses \n (Unix), \r\n (Windows), or 
>>> > \r (classic 
>>> > Mac) line endings. Likewise, when the compiler strips the initial and 
>>> > final newline 
>>> > from the literal value, it will strip one of any of the \n, \r\n, or \r 
>>> > line-ending 
>>> > sequences from both ends of the literal.
>>> > 
>>> > // equal to "foo\nfoo\nfoo\nfoo"
>>> > """^J
>>> > foo^M^J
>>> > foo^J
>>> > foo^M
>>> > foo^M
>>> > """
>>> > 
>>> > - It should be clarified that *multiline strings support the same escapes 
>>> > and 
>>> > interpolations* as single-line strings. This allows a literal """ to be 
>>> > written \""". 
>>> > Discussion on the list 

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

2017-04-19 Thread Kevin Nattinger via swift-evolution
Not to mention that many IDEs (at least have options to) trim trailing 
whitespace automatically, so it has a fair to high likelihood of breaking 
unexpectedly and invisibly.

> On Apr 19, 2017, at 3:09 PM, Joe Groff via swift-evolution 
>  wrote:
> 
> 
>> On Apr 19, 2017, at 3:07 PM, Xiaodi Wu > > wrote:
>> 
>> Hmm, I don't know that I agree. What's the harm of trailing spaces, and if a 
>> warning, how would I silence it given that \ is rejected as a way to 
>> suppress a literal newline?
> 
> \("") comes to mind, if nothing else. Other common tools like Git already 
> flag trailing whitespace by default, so even if Swift doesn't warn about it, 
> you might still need to satisfy other tools in your pipeline.
> 
> -Joe
> 
>> 
>> On Wed, Apr 19, 2017 at 17:02 Joe Groff via swift-evolution 
>> > wrote:
>>> On Apr 19, 2017, at 2:43 PM, Adrian Zubarev 
>>> > 
>>> wrote:
>>> 
>>> First of all, thank you for accepting the proposal. However I still have 
>>> one single concern left about the trailing whitespaces. Will the final 
>>> implemented version raise a warning or produce an error when there are 
>>> trailing whitespaces?
>>> 
>>> The whole idea of a trailing \ was in first place to prevent new line 
>>> injection but also for trailing whitespace character precision.
>>> 
>>> The following example could have 1000 characters, but a different developer 
>>> who reads the code wouldn’t even notice.
>>> 
>>> """
>>> Foo…
>>> Bar
>>> """
>>> That’s what the trailing backslash was meant for. To prevent unwanted 
>>> whitespaces, or if you really need them, to force you to be precise about 
>>> them.
>>> 
>>> """
>>> Foo\n\
>>> Bar
>>> """
>> 
>> That seems like a reasonable thing to warn about. That also reminds me, 
>> blank lines should be accepted within a literal even if they aren't 
>> "indented" with invisible whitespace.
>> 
>> -Joe
>> 
>> ___
>> 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 in-place removeAll to the std lib

2017-04-10 Thread Kevin Nattinger via swift-evolution
array.remove(where: { $0 > 3 })
array.remove { $0 > 3 }

> On Apr 10, 2017, at 12:25 PM, David Hart via swift-evolution 
>  wrote:
> 
> 
> 
> On 10 Apr 2017, at 17:17, Maximilian Hünenberger via swift-evolution 
> > wrote:
> 
>> How about this:
>> 
>> array.removeEvery(3)
>> array.removeEvery{ $0 > 3 }
>> 
>> I think it preserves the meaning while it reads nicely. However "every" has 
>> no precedent in other functions, as far as I know.
> 
> Every has a very ambiguous meaning in English. It could be understood as 
> "every 3 values" as in 0, 3, 6, 9, etc...
> 
>> Am 10.04.2017 um 04:32 schrieb Ben Cohen via swift-evolution 
>> >:
>> 
>>> 
 On Apr 8, 2017, at 5:41 PM, Brent Royal-Gordon > wrote:
 
> On Apr 8, 2017, at 12:44 PM, Xiaodi Wu via swift-evolution 
> > wrote:
> 
> +1. Perfect. Let's not bikeshed this and get it done!
 
 
 Sorry, I'm going to have to insist on bikeshedding.
 
 `equalTo:` is kind of ugly and has no precedent in the standard library. 
 Similar APIs seem to either leave the parameter unlabeled or use `of:` (as 
 in `index(of:)`). I think unlabeled is probably the right answer here.
 
>>> 
>>> I think removeAll(of:) works well for the equatable value version.
>>> 
>>> FWIW of all the ideas from the all thread, containsOnly(_:) for the 
>>> equatable value version works for me. It has a nice symmetry: contains(3) 
>>> vs containsOnly(3).
>>> 
 The main shortcoming I can see is that if you see:
 
array.removeAll(3)
 
>>> 
>>> Personally don’t feel good about an unlabelled version. It doesn’t read 
>>> right. Remove all three what?
>>> 
 You might think `3` is either an index or a count. But neither of those 
 actually make sense:
 
 * It can't be an index because then `All` would have no meaning. There's 
 only ever one thing at a given index. Besides, indices are almost always 
 marked with `at:` or another parameter label.
 * It can't be a count because `All` is already a count. What could "remove 
 all 3" possibly mean if the array doesn't happen to have three elements?
 
 And this is only a problem if the value happens to be an integer. If it's 
 anything else, the type makes clear that this can't possibly be an index 
 or count; it must be an element.
 
 (But if you really do think this is insurmountable, `removeAll(of: 3)` 
 *is* impossible to misinterpret and fits in better than 
 `removeAll(equalTo:)`.)
 
 (P.S. The existing oddness of `removeFirst(_:)` compared to 
 `removeFirst()` and `removeAll()` is why I proposed last year that it be 
 renamed to `removePrefix(_:)`, which matches the count-taking `prefix(_:)` 
 method.)
 
 -- 
 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 
>> 
> ___
> 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] switch must be exhaustive, consider adding a default clause

2017-04-10 Thread Kevin Nattinger via swift-evolution

> On Apr 10, 2017, at 9:18 AM, Josh Parmenter via swift-evolution 
>  wrote:
> 
> case .none isn’t handled.

It shouldn’t need to be handled in the second switch because it’s impossible. 
Not just developer thinks “impossible” but easily provable by static analysis 
the compiler is doing it anyway—I wouldn’t be surprised if including the case 
resulted in an “unreachable code” warning (in fact, it probably should).

> This should probably be on the swift-users list though, no?

File a bug, IMO. 

> Best,
> Josh
> 
> 
> 
> On Apr 8, 2017, at 11:29 AM, Drew Crawford via swift-evolution 
>   >> wrote:
> 
> 
> 
> Is there a good reason we do not compile this:
> 
> import UIKit
> 
> func foo(operation: UINavigationControllerOperation) {
>switch(operation) {
>case .push: /* snip */ break
>case .pop: /* snip */ break
>default:
>preconditionFailure("This is a silly operation")
>}
>switch(operation) {
>case .push: /* snip */ break
>case .pop: /* snip */ break
> //error: Switch must be exhaustive, consider adding a default clause
>}
> }
> 
> The switch *is* exhaustive, because the default case is unreachable.  The 
> compiler could infer as much from branch analysis.
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
>  >
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 
> 
> 
> Joshua Parmenter | Engineering Lead, Apple Technologies
> 
> T 248 777 
> C 206 437 1551
> F 248 616 1980
> www.vectorform.com  >
> 
> Vectorform
> 2107 Elliott Ave Suite 303
> Seattle, WA  98121 USA
> 
> Think Tank. Lab. Studio.
> We invent digital products and experiences.
> 
> SEATTLE | DETROIT | NEW YORK | MUNICH | HYDERABAD
> ___
> 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-09 Thread Kevin Nattinger via swift-evolution

> On Apr 9, 2017, at 9:29 AM, John Holdsworth via swift-evolution 
>  wrote:
> 
> Looking at 3) which is underspecified in the proposal perhaps, I’d consider 
> it a “feature" but I can see it would be too magical for some. To specify it 
> more you could say: if there is only whitespace between the last newline and 
> the end of a multiline literal this whitespace will be stripped from all 
> lines in the literal. If lines do not start with this exact sequence of 
> whitespace a warning is emitted. In addition, if the first character in the 
> literal is a newline it will be removed. This operation could be made 
> explicit e.g. #trimLeft(“”"a literal"”")

Yeah, that was my one hesitation. I actually didn’t understand the scheme at 
first and thought *all* whitespace would be left-trimmed. What about just 
adding a `leftTrimLines()` or `deindent()`+`deindent(levels:Int)` or comparable 
string method, so you could just do something like this:

let json = """
{
"a": "b",
"c": {
"d": 3
}
}
""".deindent()

As a bonus, you can use this for non-literals should the need arise.

> 
> Perhaps we can find common ground on 1) and 2) and even 3) with a view to 
> resubmitting if there is time. Seems mostly like we just need to discuss the 
> delimiter further and decide whether the indent trimming is a bug or a 
> feature to keep moving and not let another year slip by.

I’d really rather just see the core team accept this with a modification to 
trimming, otherwise I guarantee it’s not getting in this year.

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


Re: [swift-evolution] [Pitch] Remove type-inference for stored property

2017-04-09 Thread Kevin Nattinger via swift-evolution
I am 110% AGAINST this change.  Having complex expressions as a stored property 
initializer is bad practice anyway, and having the type prefixed in that case 
provides at best marginal improvement in clarity and doesn’t fix the underlying 
problem.  

Type inference on simple expressions allows you to put the emphasis on the 
value, rather than the type—e.g. `let defaultTimeout = 5 as TimeInterval` is 
way easier to read and understand than `let defaultTimeout: TimeInterval = 5`; 
and it only gets worse if you declare something with a long class name—`let 
fooBarBazzerciser: MyReallyReallyLongType = MyReallyReallyLongType(argumentOne: 
1, argumentTwo: 2)`—you might even have to scroll horizontally just to see what 
the arguments are! Clarity lost, none gained.


> On Apr 9, 2017, at 3:04 PM, T.J. Usiyan via swift-evolution 
>  wrote:
> 
> I would be alright with this change. The slight inconvenience, even in 
> teaching, would be worth it, in my opinion. It is easier for developers to 
> reason about the types intended when they are made explicit.
> 
> On Sun, Apr 9, 2017 at 6:01 PM, Jon Shier via swift-evolution 
> > wrote:
>   I generally dislike any language change desired because it makes the 
> compiler implementation easier. We saw a few such changes for Swift 3 and all 
> of them were net negatives for the actual users of the language (to a minor 
> extent for most, to be fair).  I would hope that, as the compiler matures, 
> these types of inference performance issues will become less of a problem. 
> Removing a rather nice language feature, especially one that plays such a big 
> role in the “feel” of the language, for short term gain seems rather 
> shortsighted to me.
> 
> 
> 
> Jon Shier
> 
> 
> 
>> On Apr 9, 2017, at 11:23 AM, Lucas Neiva via swift-evolution 
>> > wrote:
>> 
>> If inference only works in simple cases, I think it would seem like it works 
>> unpredictability to anyone unfamiliar with the implementation details.
>> 
>> I image the question of "why do I have to declare a type here, but not in 
>> this case?" coming up.
>> 
>> Declaring types is one of the first things you have to learn anyway. Just 
>> declaring a function already requires some understanding of types. 
>> Properties are not much different IMO.
>> 
>> On 8 Apr 2017, at 08:34, Brent Royal-Gordon via swift-evolution 
>> > wrote:
>> 
 On Apr 7, 2017, at 12:21 AM, Daniel Duan via swift-evolution 
 > wrote:
 
 The cons for doing this are obvious too: the inference makes the language 
 feels more friendly and is, undoubtedly, a beloved feature for many. This 
 would be a source breaking change.
>>> 
>>> 
>>> Beyond just being more friendly, I think it could be considered a teaching 
>>> issue. A great way to introduce beginners to custom types would be 
>>> something like:
>>> 
>>> struct Point {
>>> var x = 0.0
>>> var y = 0.0
>>> }
>>> 
>>> Or:
>>> 
>>> struct Person {
>>> var name = ""
>>> var age = 18
>>> }
>>> 
>>> If you have to explicitly specify types for the properties, that's another 
>>> thing you need to introduce to people before you can do this.
>>> 
>>> On the other hand, a very limited form of inference might be fine here. 
>>> Imagine if we did a sort of limited, single-pass, top-down inference which 
>>> only understood a few things (literals, tuple syntax, initializer calls), 
>>> stopped once it had seen enough to infer a complete type, and rejected an 
>>> expression if it encountered something it didn't understand before 
>>> finishing. That would probably cover most simple cases, and it would 
>>> probably only allow expressions whose types were obvious enough that we 
>>> could use it for arguments, too. (But of course it would mean more code in 
>>> the compiler, so it might not be worth it.)
>>> 
>>> -- 
>>> 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 
>> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 

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

2017-04-06 Thread Kevin Nattinger via swift-evolution

> On Apr 6, 2017, at 6:10 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of SE-0169 "Improve Interaction Between private Declarations and 
> Extensions" begins now and runs through April 11, 2017. The proposal is 
> available here:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0169-improve-interaction-between-private-declarations-and-extensions.md
>  
> 
> ...
> 
> What is your evaluation of the proposal?
Strong +1. This would eliminate most of the need to unnecessarily expose 
private state to scopes where it doesn’t belong.

> Is the problem being addressed significant enough to warrant a change to 
> Swift?
Very much so. I was surprised and disappointed to find out that private didn’t 
work this way already when 3 came out.

> Does this proposal fit well with the feel and direction of Swift?
Yes, it’s an important and necessary step.
Swift encourages splitting class implementations into a number of extensions 
for logical grouping, protocol conformance, etc. Currently, implementing 
classes this way often requires bumping private members to fileprivate, thereby 
dangerously exposing them to any other classes in the file.

> If you have used other languages or libraries with a similar feature, how do 
> you feel that this proposal compares to those?
Most languages don’t have this problem because the primary implementation isn’t 
normally broken into pieces in the same way.  I’d argue that the set of 
declaration + extensions that make up the primary body of the class are 
together equivalent to a single-body declaration in other languages, and 
therefore privates should be available to all pieces thereof.
> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?
Followed the several discussions about file/private access over the last year 
or two, and contributed to the current one.

> 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-06 Thread Kevin Nattinger via swift-evolution

> On Apr 6, 2017, at 2:35 PM, Joe Groff via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of SE-0168 "Multi-Line String Literals" begins now and runs 
> through April 12, 2017. The proposal is available here:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>  
> 
> ...
>   • What is your evaluation of the proposal?

+1
We definitely need a multi-line string solution, and I’m a fan of the 
python-like “”” solution.  

>   • Is the problem being addressed significant enough to warrant a change 
> to Swift?

Yes

>   • Does this proposal fit well with the feel and direction of Swift?

Yes

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

Favorably.
This is Largely the same as python, with the addition of leading-space 
stripping, the lack of which is one of the biggest gripes I’ve had and seen 
with python’s “”” implementation.

>   • How much effort did you put into your review? A glance, a quick 
> reading, or an in-depth study?

Followed both the original discussion and the recent revival closely. 

> 
> More information about the Swift evolution process is available at:
> 
> https://github.com/apple/swift-evolution/blob/master/process.md 
> 
> 
> Thank you,
> 
> -Joe
> 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] Type-based ‘private’ access within a file

2017-04-06 Thread Kevin Nattinger via swift-evolution
>> On Apr 5, 2017, at 6:54 PM, Nevin Brackett-Rozinsky via swift-evolution 
>> > wrote:
>> 
>> On Wed, Apr 5, 2017 at 12:02 AM, Chris Lattner via swift-evolution 
>> > wrote:
>> 
>>  - fileprivate should really become much more rare, which makes it more 
>> meaningful and significant where it occurs.  This was the original idea and 
>> intent behind SE-0025.
>> 
>> I would like to understand the reasoning here. I just looked back at SE-0025 
>> and I see this same assertion, but I cannot find the reasoning. Could you 
>> explain it to me please?

The idea of a private member is that it’s only visible within the class that 
declares it. In languages where the class is traditionally declared all at 
once, that’s straightforward enough; however, the tradition of implementing 
swift classes as a series of extensions (currently) forces opening much more 
than should be to any other classes within the file.  If class B needs access 
to one private within class A, it also gets access to every single variable 
used by an extension to A, and every single function used by an extension 
outside the one it’s declared in. That’s way more visibility into the class 
than it should have.

>> 
>> Certainly I would love to make the *spelling* of “fileprivate” be entirely 
>> nonexistent. But all the lines of logic I have come up with lead inexorably 
>> to the conclusion that the *semantics* of “fileprivate” should be the 
>> common, de facto, access level that people reach for when they need 
>> encapsulation.
>> 
>> 1. Someone makes a file with a single type in it, and marks the 
>> implementation details “private”. At this point, it does not matter matter 
>> which meaning “private” has, they all work the same so far.
>> 
>> 2. The developer adds a free function to the file. Or an extension of 
>> another type. Or another type entirely. And they put it in the same file 
>> because it needs to work with the implementation details of the existing 
>> type.

IMO having a free function access the internals of an object is a huge code 
smell. It should almost always be a function on the object or the class. And 
I’d be highly skeptical of any architecture that requires one class to access 
another class’s privates directly.  In general, I’m fairly strongly opposed to 
having multiple externally accessible classes in the same file (probably 
influenced by having used Java through most of my education).

>> 
>> Now the difference between possible meanings of “private” matters. And if it 
>> is anything short of “fileprivate”, then the developer has to go back and 
>> change access levels. Things no longer “just work”.

Well, yes, that’s what I’d expect and want, and that’s the whole point of 
access levels. If I have a private member and want to use it in another class, 
I should have to make a conscious decision about whether to open up that 
member, add an externally visible one, or just do it a different way entirely. 
(One might argue based on that point that the fix-it to widen the access level 
is actually harmful.) I’m not sure what your point is here, but I think forcing 
the dev to stop and think about whether the access needs to be loosened is a 
*good* thing.

>> 
>> The alternative scenario is that one adds something to the file which 
>> doesn’t need privileged access to what’s already there. In which case the 
>> questions are, “Why put it in the same file at all?” and “If there is a good 
>> reason to put it in the same file, is there any *harm* in it being able to 
>> see private members?”

Again I’m not seeing your point. Yes, you should think twice about why it’s in 
the same file. Yes, there is harm because it can now see fileprivate members 
that it shouldn’t.

>> 
>> Most developers most of the time should not have to think about 
>> sub-file-level granularity. If things are in the same file it is because 
>> they need to work together closely. We should be able to mark members 
>> “private” and work with them across the file. This dramatically reduces the 
>> cognitive burden, and the amount of time spent fiddling with access levels.

Are you arguing for reverting to the Swift 2 definition of private = modern 
fileprivate? 

I’d argue exposing privates to everything in a file actually *increases* 
cognitive load because now I have to keep track of which classes are declared 
in the same file. If private has a sane meaning (initial declaration + 
“primary” extensions, the level under consideration here) only the class I know 
I’m working in has access. Much simpler and context-free.

>> 
>> With any meaning of “private” less than “fileprivate”, developers end up 
>> marking things “private”, then letting the IDE change it to “fileprivate” 
>> when the compiler complains. This tells me that people actually want the 
>> semantics of “fileprivate”, and they want it to be spelled “private”.

Re: [swift-evolution] [Pitch] Add an all algorithm to Sequence

2017-04-05 Thread Kevin Nattinger via swift-evolution
I definitely think we should stick with `all` and an appropriate argument 
label. It’s a term of art and the label makes it perfectly clear what to expect.
That said, `all(match)` and `all(equal)` sound to me like they expect an object 
to compare each against (func all(equal needle: Element))
I suggest something like `all(pass:)`. 

> On Apr 5, 2017, at 4:34 PM, Brandon Trussell via swift-evolution 
>  wrote:
> 
> I retract my gripes on the original names also.  The argument labels make the 
> intent of the method clear. 
> 
> On Wed, Apr 5, 2017 at 11:23 AM, Thorsten Seitz via swift-evolution 
> > wrote:
> +1
> 
> Am 03.04.2017 um 10:29 schrieb Daniel Duan via swift-evolution 
> >:
> 
>> I want to retract my nitpickings on argument labels; `all(equal:)` and 
>> `all(match:)` are the best names for these methods.
>> 
>> things all match condition?
>> things all equal value?
>> 
>> If we accept `all` as a term of art (which I think we should), along with 
>> these labels the use site are very readable!
>> 
>>> On Mar 31, 2017, at 6:38 PM, Daniel Duan via swift-evolution 
>>> > wrote:
>>> 
>>> nit: should these names be `all(matching)`/`all(equalTo)` per API Design 
>>> Guidelines?
 On Mar 31, 2017, at 8:28 AM, Ben Cohen via swift-evolution 
 > wrote:
 
 Hi,
 
 A short proposal for you as part of the algorithms theme. Hopefully 
 non-controversial, aside from the naming of the method and arguments, 
 about which controversy abounds. Online copy here: 
 https://github.com/airspeedswift/swift-evolution/blob/9a778e904c9be8a3692edd19bb757b23c54aacbe/proposals/0162-all-algorithm.md
  
 
 
 
 Add an all algorithm to Sequence
 
 Proposal: SE- <>
 Authors: Ben Cohen 
 Review Manager: TBD
 Status: Awaiting review
 Introduction
 
 It is common to want to confirm that every element of a sequence equals a 
 value, or matches a certain criteria. Many implementations of this can be 
 found in use on github. This proposal adds such a method to Sequence.
 
 Motivation
 
 You can achieve this in Swift 3 with contains by negating both the 
 criteria and the result:
 
 // every element is 9
 !nums.contains { $0 != 9 }
 // every element is odd
 !nums.contains { !isOdd($0) }
 but these are a readability nightmare. Additionally, developers may not 
 make the leap to realize contains can be used this way, so may hand-roll 
 their own for loop, which could be buggy, or compose other inefficient 
 alternatives:
 
 // misses opportunity to bail early
 nums.reduce(true) { $0.0 && $0.1 == 9 }
 // the most straw-man travesty I could think of...
 Set(nums).count == 1 && Set(nums).first == 9
 Proposed solution
 
 Introduce two algorithms on Sequence which test every element and return 
 true if they match:
 
 nums.all(equal: 9)
 nums.all(match: isOdd)
 Detailed design
 
>> ___
>> 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 
> 
> 
> 
> 
> 
> -- 
> Brandon
> ___
> 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] [swit-evolution] [Review] SE-0156: Class and Subtype existentials

2017-03-01 Thread Kevin Nattinger via swift-evolution
> What is your evaluation of the proposal?
+0.9
The core of the proposal is unquestionably necessary to correct a serious 
deficiency in the expressivity of the type system, but I take issue with the 
arbitrary limitation of requiring the concrete type to be first and would give 
a full +1 to the core team accepting with the modification of removing that 
limitation.

> Is the problem being addressed significant enough to warrant a change to 
> Swift?
Definitely. I’ve run into the issue this would solve several times in 
real-world applications.

> Does this proposal fit well with the feel and direction of Swift?
Yes

> If you have used other languages or libraries with a similar feature, how do 
> you feel that this proposal compares to those?
Basically a direct translation of the objc feature.

> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?

Followed and to some extent participated in the discussion, relatively quick 
read of the final proposal.

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


Re: [swift-evolution] A Comprehensive Rethink of Access Levels in Swift

2017-02-25 Thread Kevin Nattinger via swift-evolution
> …
> Additionally, the design allows ‘final’ to take any one of those visibility 
> levels as a parameter, to indicate that the type should be treated as ‘final’ 
> at and above the specified scope. Thus ‘final(public)’ prevents subclassing 
> outside the module, while ‘final(internal)’ prevents it outside the ‘private’ 
> scope. For consistency, ‘final(private)’ is also permitted, although it means 
> the same thing as ‘final’ by itself.

I feel final(public) could be confusing given how we currently have 
private(get/set). What about public(final)? That’s at least consistent with 
current access syntax.

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


Re: [swift-evolution] [Pitch/Reality Check] Allow instance members as parameter default values

2017-02-22 Thread Kevin Nattinger via swift-evolution

> On Feb 22, 2017, at 8:25 PM, Derrick Ho via swift-evolution 
>  wrote:
> 
> Did you know you can use a static variable as a default parameter?
> 
> class poncho {
> static var color= "yellow"
> 
> func foo(color: String = poncho.color){}
> }
> 
> I think instance members should not be allowed as default members though. It 
> may lead to unexpected behavior.

Could you explain or give an example of how the behavior would be unexpected?

> On Wed, Feb 22, 2017 at 11:06 PM T.J. Usiyan via swift-evolution 
> > wrote:
> +1 if this doesn't have terrible implications. 
> 
> The downside to making it IUO or Optional is that that changes the type 
> signature of  `index(i:offsetBy:)` for no reason other than a default value. 
> If you decide to change to or away from providing a default value it probably 
> shouldn't change the type accepted in that spot. 
> 
> On Wed, Feb 22, 2017 at 7:32 PM, Ben Cohen via swift-evolution 
> > wrote:
> 
>> On Feb 22, 2017, at 10:42 AM, Nate Cook via swift-evolution 
>> > wrote:
>> 
>> Oops, left out that there's this horrifying way of writing it right now:
>> 
>> extension Collection {
>> func index(_ i: Index! = nil, offsetBy n: IndexDistance) -> Index {
>> let i = i ?? startIndex
>> // ...
>> }
>> }
>> 
>> Nobody wants that.
>> 
> 
> Oh I don’t think it’s all that bad! It also doesn’t need to be an IUO, since 
> you’re unwrapping it immediately into another variable no matter what.
> 
> This also gives you the flexibility to write this:
> 
> extension Collection {
> func index(_ i: Index? = nil, offsetBy n: IndexDistance) -> Index {
> let i = i ?? (n < 0 ? endIndex : startIndex)
> // ...
> }
> }
> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [pitch] Make swift enum string available to Objc

2017-02-20 Thread Kevin Nattinger via swift-evolution
I don’t think we need/want to add `@objcstring` or anything like that, but I do 
think we should let String enums be @objc (currently it’s int types only) and 
imported as const refs.

// Already works
@objc enum IntEnum: Int {
case foo = 1
case bar = 2
}

// "not an integer type"
// Should be allowed.
@objc enum StrEnum: String {
case foo
case bar = "baz"
}

Becomes

// Current
typedef NS_ENUM(NSInteger, IntEnum) {
IntEnumFoo = 1,
IntEnumBar = 2
};

// Proposed (static or extern, depending on implementation)
NSString *const StrEnumFoo = @“foo";
NSString *const StrEnumBar = @“baz";

In fact, I’d go a step further and say any RawRepresentable enum as a globally 
initialized const in objc should be allowed the same treatment. Though the only 
other type that comes to mind is float/double.

> On Feb 20, 2017, at 4:07 PM, Derrick Ho via swift-evolution 
>  wrote:
> 
> Swift should not forsake objective-c.  At least not when it comes enum 
> strings.  Although swift enums are suppose to be swift only, I think we 
> should add a new attribute to slightly relax that.  I think a good attribute 
> would be @objcstring.
> 
> By adding @objcstring, an objective-c exclusive class will be generated.
> 
> @objcstring
> enum Planet {
>   case Jupiter
> }
> 
> I have written up a proposal with more details on what it would look for 
> objective-c.
> 
> https://github.com/wh1pch81n/swift-evolution/blob/swift-enum-objc/proposals/-Swift-enum-strings-ported-to-Objective-c.md
>  
> 
> 
> If no one objects to this proposal I'll submit it.
> 
> **notes: I am reviving this discussion so that I may submit this for Swift 4 
> stage 2
> ___
> 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] [Proposal] [Stage–2] `return` consistency for single-expressions

2017-02-18 Thread Kevin Nattinger via swift-evolution

> On Feb 18, 2017, at 7:33 PM, Chris Lattner via swift-evolution 
>  wrote:
> 
> 
>> On Feb 17, 2017, at 12:20 AM, Adrian Zubarev via swift-evolution 
>> > wrote:
>> 
>> I’d like to revive an additive proposal that couldn’t make it into Swift 3. 
>> This proposal has a small improvement to the language compared to other big 
>> features currently being proposed. It almost feels like a bug fix rather 
>> than a new feature, but it still needs a full and quick review process.
>> 
>> You can read the formatted version here: 
>> https://github.com/apple/swift-evolution/pull/608 
>> 
> Just MHO, but I consider this syntactic sugar, not a fundamental feature that 
> fits the goal of Swift 4 stage 2.  

Not that I’m necessarily in favor of this change, but my impression was that 
the whole point of stage 1/2 was that anything not allowed in stage 1 is fair 
game in stage 2 (if it happens; that doesn’t seem to be likely at this point). 
What exactly is the goal of stage 2 then, should there actually be time for it?

> 
> I’m also pretty opposed to doing it at any time.  The rationale of “implicit 
> return” in closures is specifically because they are limited to a single 
> expression, which makes the semantics “obvious”.  This was carefully 
> considered.
> 
> -Chris
> 
> ___
> 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] Typed throws

2017-02-17 Thread Kevin Nattinger via swift-evolution

> On Feb 17, 2017, at 11:50 AM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> Sorry, I couldn’t follow every thread. I simply couldn’t get that fact from 
> the given context of the first post by Anton. :) Just forget everything I 
> mentioned about typealias, because it was based on the assumption of an error 
> list.
> 
> Anyways +1 for typed throws. The syntax throws(T) and rethrows(T) is fine by 
> me.
> 
I feel like rethrows can and should be inferred. It’s just a pass-through.

> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 17. Februar 2017 um 20:45:55, Matthew Johnson (matt...@anandabits.com 
> ) schrieb:
> 
>> 
>>> On Feb 17, 2017, at 1:42 PM, Adrian Zubarev via swift-evolution 
>>> > wrote:
>>> 
>>> So the typed throws are going to be limited to a single error type, is that 
>>> the direction we're heading to?
>> 
>> Yes, this topic was discussed thoroughly last year.
>> 
>>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> Am 17. Februar 2017 um 20:39:12, Anton Zhilin (antonyzhi...@gmail.com 
>>> ) schrieb:
>>> 
 In this case, you’d better create a new error type, which includes all the 
 cases of those errors:
 
 // FileNotFoundError and WrongFormat are Error-s
 
 struct PreferencesError : Error {
 init(_: FileNotFoundError)
 init(_: WrongFormat)
 // ...
 }
 
 func readPreferences() throws(PreferencesError)
 In the most “lazy” case, you’d just create an enum of those two:
 
 enum PreferencesError : Error {
 case fileNotFound(FileNotFoundError)
 case wrongFormat(WrongFormatError)
 }
 Better yet, you should analyze, which cases are meaningful for user of 
 readPreferences, and present them with appropriate interface. You may want 
 to crash on those cases of initial error types, with which you can’t do 
 anything on the level of abstraction of readPreferences. Some of the 
 others will be merged or renamed.
 
 With proper error types, a single type in throws clause is enough, without 
 sum types.
 
 2017-02-17 22:22 GMT+03:00 Adrian Zubarev via swift-evolution 
 >:
 
 
 Sure thing, but that’s not what I was asking about. Kevin made a protocol 
 that conforms to Error where all the his enums conformed to MyError 
 protocol. That way we’re losing all enum cases and are not really a step 
 further as before.
 
 
>>> ___
>>> 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] Typed throws

2017-02-17 Thread Kevin Nattinger via swift-evolution
protocol MyError: Error {}
enum MyFooError: MyError { … }
enum MyBarError: MyError { … }

func baz() throws(MyError)

> On Feb 17, 2017, at 11:03 AM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> I suggest we need to find a way to shorten the list of the possible error 
> types with a the help of typeallias
> 
> extension MyError1: Error { ... }
> extension MyError2: Error { ... }
> extension MyError3: Error { ... }
> 
> typealias MyErrors = MyError1 | MyError2 | MyError3  
> 
> func foo() throws(MyErrors) -> MyResult
> func bar(_: () throws(T) -> Void) rethrows(MyErrors, T) -> MyResult
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 17. Februar 2017 um 19:47:47, Anton Zhilin via swift-evolution 
> (swift-evolution@swift.org ) schrieb:
> 
>> Now this is on-topic, I guess.
>> Last time we stopped at John McCall’s syntax:
>> 
>> extension MyError: Error { ... }
>> 
>> func foo() throws(MyError) -> MyResult
>> It’s conservative and prevents visual ambiguity with extra parentheses.
>> 
>> If we (somewhat) agree on this, then submitting a proposal will be trivial.
>> 
>> ___
>> 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: Replacement for FileHandle

2017-02-15 Thread Kevin Nattinger via swift-evolution

> On Feb 15, 2017, at 3:45 PM, Tony Parker via swift-evolution 
>  wrote:
> 
>> 
>> On Feb 15, 2017, at 2:25 PM, Charles Srstka > > wrote:
>> 
>>> On Feb 15, 2017, at 3:11 PM, Itai Ferber >> > wrote:
>>> 
>>> FYI, Tony is the manager of the Foundation team. :)
>>> We care very much about making sure that the experience of using our 
>>> framework is a positive one — the more Radars we get, the better we can 
>>> prioritize improving APIs that are not working as well as they could be for 
>>> our users. Even if the Radar gets duped to an existing one, thats one more 
>>> +1 for that Radar saying "this is a problem".
>>> 
>> Yeah I know, but it’s a frustrating experience, spending a half hour writing 
>> a detailed bug report (sometimes with videos attached to demonstrate the 
>> issue), just to effectively do the same thing as spending 5 seconds to hit 
>> the +1 button on most issue trackers you come across.
>> 
>> Especially since you never find out what happened to the original bug 
>> report. You can see if it’s open or closed, but did they fix it in some 
>> internal build? Did they decide it “behaves correctly?” Did somebody just 
>> skim your report, and mistakenly attach it to some other, unrelated issue? 
>> There’s no way to know.
>>> I will search for your old Radar, but in any case, please do file a new one 
>>> about this, and about any other issues you have, because we are indeed 
>>> listening.
>>> 
>> 
>> I was pretty sure I'd submitted something way, way back in the misty days of 
>> yore, but I can’t find it. I’ve filed a couple of new ones: rdar://30543037 
>>  and rdar://30543133 .
>> 
>> Charles
>> 
> 
> Thanks for filing these.
> 
> Sometimes, for process reasons, we do indeed mark bugs as dupes of other 
> ones. Usually the polite thing to do is to dupe to the earliest filed one. 
> Sometimes this comes across with an appearance of not caring to the filer of 
> the new bug,

At the risk of getting off-topic, I think it would defuse a lot of developer 
frustration around that to just show the status (open/fixed/wontfix/correct) of 
the root bug.  Filed radar 30551245 suggesting as much ;-)

> but our intent is simply to consolidate the reports we have so that we know 
> that the issue is serious.
> 
> We do not make API changes without going through a vigorous review process, 
> to avoid churn for the many clients above us. The flip side is that this can 
> take some time. I’m sure you understand that all software engineering is 
> about tradeoffs.
> 
> All of that said, we’ll take a look at these and see what improvements we can 
> make here. As I said, I’m not a fan of exception-based API.
> 
> - Tony
> 
> 
> ___
> 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] for-else syntax

2017-02-01 Thread Kevin Nattinger via swift-evolution
I ran into this not too long ago. Something to handle this case would 
definitely be nice, but I agree we shouldn’t take python’s syntax with 
different semantics.

> On Feb 1, 2017, at 9:30 AM, Dimitri Racordon via swift-evolution 
>  wrote:
> 
> I agree. A for-else loop with different semantics than python would be 
> error-prone for many people.
> 
> 
>> On 1 Feb 2017, at 18:17, Jacob Bandes-Storch via swift-evolution 
>> > wrote:
>> 
>> One possible con: this is subtly but extremely different from Python, where 
>> a for loop's else clause is executed only if there was no `break` from the 
>> loop.
>> On Wed, Feb 1, 2017 at 8:48 AM Chris Davis via swift-evolution 
>> > wrote:
>> Hi,
>> 
>> Often when I’m programming I stumble upon this scenario:
>> 
>> I have a list of items that may or may not be empty - if it’s full, I do one 
>> thing, if it’s empty I do something else, my code looks like this:
>> 
>> class Example_1
>> {
>> let names = ["Chris", "John", "Jordan"]
>> 
>> /// Loop over names, if no names, print no names
>> func run()
>> {
>> for name in names
>> {
>> print(name)
>> }
>> 
>> if names.count == 0
>> {
>> print("no names")
>> }
>> }
>> }
>> 
>> let exampleOne = Example_1()
>> exampleOne.run()
>> 
>> However, Personally, I would find it more pleasing to write something like 
>> this:
>> 
>> class Example_2_Proposed
>> {
>> let names:[String] = []
>> 
>> /// Loop over names, if no names, print no names
>> func run()
>> {
>> for name in names
>> {
>> print(name)
>> } else {
>> print("no names")
>> }
>> }
>> }
>> 
>> let exampleTwo = Example_2_Proposed()
>> exampleTwo.run()
>> 
>> The difference here is a “for-else” type syntax where if there were no items 
>> in the array it would simply fall through to the else statement.
>> 
>> What would be the pros/cons of introducing such syntax?
>> 
>> Is there’s a way of doing something similar in swift already?
>> 
>> Thanks
>> 
>> Chris
>> 
>> 
>> 
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] Subclass Existentials

2017-01-29 Thread Kevin Nattinger via swift-evolution
+1 on including concrete types, this is currently a gaping hole in the language.
-100 on requiring the concrete type to be first. If I want to specify the types 
alphabetically, grouped by module, or any other way I choose, why should I not 
be allowed to do so? The compiler can warn on redundancies and error on 
contradictions, that’s all we really need.

> On Jan 29, 2017, at 8:39 AM, David Hart via swift-evolution 
>  wrote:
> 
> Hello,
> 
> As promised, I wrote the first draft of a proposal to add class requirements 
> to the existential syntax. Please let me know what you think.
> 
> https://github.com/hartbit/swift-evolution/blob/subclass-existentials/proposals/-subclass-existentials.md
>  
> 
> 
> Regards,
> David.
> 
> Existentials for classes conforming to protocols
> 
> Proposal: SE- 
> 
> Authors: David Hart , Austin Zheng 
> 
> Review Manager: TBD
> Status: TBD
>  
> Introduction
> 
> This proposal brings more expressive power to the type system by allowing 
> Swift to represent existentials of classes and subclasses which conform to 
> protocols.
> 
>  
> Motivation
> 
> Currently, the only existentials which can be represented in Swift are 
> conformances to a set of protocols, using the :
> 
> let existential: Hashable & CustomStringConvertible
> On the other hand, Objective-C is capable of expressing existentials of 
> subclasses conforming to protocols with the following syntax:
> 
> UIViewController* existential;
> We propose to provide similar expressive power to Swift, which will also 
> improve the bridging of those types from Objective-C.
> 
>  
> Proposed
>  solution
> 
> The proposal keeps the existing & syntax but allows the first element, and 
> only the first, to be of class type. The equivalent declaration to the above 
> Objective-C declaration would look like this:
> 
> let existential: UIViewController & UITableViewDataSource & 
> UITableViewDelegate
> As in Objective-C, this existential represents classes which have 
> UIViewController in their parent inheritance hierarchy and which also conform 
> to the UITableViewDataSource and UITableViewDelegate protocols.
> 
> As only the first element in the existential composition syntax can be a 
> class type, and by extending this rule to typealias expansions, we can make 
> sure that we only need to read the first element to know if it contains a 
> class requirement. As a consequence, here is a list of valid and invalid code 
> and the reasons for them:
> 
> let a: Hashable & CustomStringConvertible
> // VALID: This is still valid, as before
> 
> let b: MyObject & Hashable
> // VALID: This is the new rule which allows an object type in first position
> 
> let c: CustomStringConvertible & MyObject
> // INVALID: MyObject is not allowed in second position. A fix-it should help 
> transform it to:
> // let c: MyObject & CustomStringConvertible
> 
> typealias MyObjectStringConvertible = MyObject & CustomStringConvertible
> let d: Hashable & MyObjectStringConvertible
> // INVALID: The typealias expansion means that the type of d expands to 
> Hashable & MyObject & CustomStringConvertible, which has the class in the 
> wrong position. A fix-it should help transform it to:
> // let d: MyObjectStringConvertible & Hashable
> 
> typealias MyObjectStringConvertible = MyObject & CustomStringConvertible
> let e: MyOtherObject & MyObjectStringConvertible
> // INVALID: The typealias expansion would allow an existential with two class 
> requirements, which is invalid
> The following examples could technically be legal, but we believe we should 
> keep them invalid to keep the rules simple:
> 
> let a: MyObject & MyObject & CustomStringConvertible
> // This is equivalent to MyObject & CustomStringConvertible
> 
> let b: MyObjectSubclass & MyObject & Hashable
> // This is equivalent to MyObjectSubclass & Hashable
> 
> typealias MyObjectStringConvertible = MyObject & CustomStringConvertible
> let d: MyObject & MyObjectStringConvertible
> // This is equivalent to MyObject & CustomStringConvertible
>  
> Source
>  compatibility
> 
> This is a source breaking change. All types bridged from Objective-C which 
> use the equivalent Objective-C feature import without the protocol 
> conformances in Swift 3. This change 

Re: [swift-evolution] Throws? and throws!

2017-01-12 Thread Kevin Nattinger via swift-evolution

> On Jan 12, 2017, at 3:50 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> Some additional thoughts: if I recall correctly from my (limited) Java days, 
> throwing in Java worked essentially like your proposed `throws!`. That the 
> Swift model expressly deviates from that example was not by accident, as far 
> as I can tell. According to the error handling docs in the Swift repo:

Java (functionally) has two types of exceptions, checked and unchecked. 
Checked exceptions must either be caught and handled or the calling method must 
be declared as throwing the same exception (or an ancestor).
Unchecked exceptions do not need to be declared, and can either be caught or 
implicitly work their way back up the stack until either they’re caught or they 
hit the top of the stack (in which case the JRE kills the program.

Objective-C’s exception system is essentially Java’s unchecked type, and 
Swift’s is checked (with the addition of requiring `try` at the call site. At 
risk of getting off on a tangent, I really dislike the raw `try` requirement. 
`try?` and `try!` at least make sense as they specify how to handle the 
exception; `try` does not.)
Swift’s exception system is basically checked exceptions; Objective-C’s is 
unchecked.

As far as I can tell, this proposal isn’t really like either; `throws?` would 
swallow the exception entirely if the caller didn’t handle it and `throws!` 
would kill the app without giving higher stack frames a chance to catch it. I’m 
really not a fan of either; I’d much prefer unchecked exceptions, and I think 
they fulfill the OP’s underlying concerns.

> 
> "Once an error is thrown, Swift will automatically propagate it out of scopes 
> (that permit it), rather than relying on the programmer to manually check for 
> errors and do their own control flow. This is just a lot less boilerplate for 
> common error handling tasks. However, doing this naively would introduce a 
> lot of implicit control flow, which makes it difficult to reason about the 
> function's behavior. This is a serious maintenance problem and has 
> traditionally been a considerable source of bugs in languages that heavily 
> use exceptions.
> 
> "Therefore, while Swift automatically propagates errors, it requires that 
> statements and expressions that can implicitly throw be marked with the `try` 
> keyword."
> 
> So I think what this is saying is that requiring `try` _every time_ is core 
> to the design of Swift error handling, and that `throws!` or even `throws?` 
> would undo it.
> 
> 
> On Thu, Jan 12, 2017 at 5:35 PM, Xiaodi Wu  > wrote:
> On Thu, Jan 12, 2017 at 4:58 PM, Jonathan Hull via swift-evolution 
> > wrote:
> I really like swift’s error handling system overall. It strikes a good 
> balance between safety and usability.
> 
> There are some cases where it would be nice to throw errors, but errors are 
> rarely expected in most use cases, so the overhead of ‘try’, etc… would make 
> things unusable. Thus fatalError or optionals are used instead.  For example, 
> operators like ‘+’ could never throw because adding ’try’ everywhere would 
> make arithmetic unbearable. But in a few cases it would make my algorithm 
> much cleaner if I just assume it will work and then catch overflow/underflow 
> errors if they happen, and resolve each of them with special cases.  Or 
> perhaps I am dealing with user entered values, and want to stop the 
> calculation and display a user visible error (e.g. a symbol in a spreadsheet 
> cell) instead of crashing.
> 
> Unless I'm mistaken, there is a performance overhead for throwing functions, 
> and thus a much greater barrier to the use cases outlined above is that the 
> performance penalty for '+' would be unacceptable in any case, whatever 
> syntactic sugar you could come up with.
>  
> I would like to propose adding ‘throws?’ and ‘throws!’ variants to ‘throws’.
> 
> These would be used for cases where error handling is not the default desired 
> behavior, but having it as an option is desired occasionally.
> 
> While I admit the idea has an appeal on a practical level, I have an 
> uncomfortable feeling about this. It's by definition true that error handling 
> is never the default desired behavior, and if I recall correctly the 
> performance of Swift error handling is tuned on the assumption that not 
> throwing is far more common than throwing. If we accept this statement at 
> face value as the justification for including `throws!`, then essentially all 
> `throws` should be `throws!`. And indeed I suspect that if the feature were 
> be implemented, that would rapidly become the case in much written Swift. In 
> essence, then, I think you're effectively proposing to invert the assignment 
> of responsibility for determining how errors are handled from the call site 
> to the declaration site, at least by default. It 

Re: [swift-evolution] Add code to super methods.

2016-11-25 Thread Kevin Nattinger via swift-evolution
I agree. An NS_REQUIRES_SUPER equivalent was on my list of things to propose 
during stage 2, and I don't see a reason to enforce order. 


> On Nov 25, 2016, at 04:42, Tino Heth via swift-evolution 
>  wrote:
> 
> 
>> What are your thoughts on this?
>> 
>> Just to throw out a strawman:
>> 
>> // Warn if override doesn’t begin with “super.foo()”
>> __attribute(swift_requires_super_call_at_begin) 
>> 
>>  // Warn if override doesn’t end with “super.foo()”
>> __attribute(swift_requires_super_call_at_end)
> 
> I myself would already be happy if Swift had an equivalent to 
> NS_REQUIRES_SUPER (preferably with a different name ;-).
> The ability to indicate that super shouldn't be called when overriding would 
> be nice as well ― both situations happen in Cocoa, and it isn't enforced, but 
> only documented.
> 
> I don't have any examples where the position of the call to super matters, 
> and my personal opinion is that this feature wouldn't pay off:
> Of course, there are situations where order is important ― but as with 
> willSet/didSet, it might only be important for the overriding class, not for 
> super.
> 
> - Tino
> ___
> 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] guard let x = x

2016-10-28 Thread Kevin Nattinger via swift-evolution

> On Oct 28, 2016, at 4:45 PM, Erica Sadun via swift-evolution 
>  wrote:
> 
> 
>> On Oct 28, 2016, at 5:00 PM, Huon Wilson > > wrote:
>> 
>> 
>>> On Oct 28, 2016, at 15:34, Erica Sadun via swift-evolution 
>>> > wrote:
>>>  
>>> Detailed
>>>  Design
>>> 
>>> unwrap can be used with any one-value enumeration. The unwrapped value is 
>>> bound to the same symbol as the associated type.
>>> 
>>> enum TypeName { case anycase(T), anothercase(U) }
>>> 
>>> // First and second are type `TypeName`
>>> let first = TypeName.anyCase(value1)
>>> let second = TypeName. anothercase(value2)
>>> 
>>> guard unwrap first else { ... }
>>> // first is now shadowed as type T
>>> 
>>> guard unwrap second else { ... }
>>> // second is now shadowed as type U
>>>  
>>> 
>> How does the compiler decide whether to succeed on anycase or succeed on 
>> anothercase respectively? In general, the compiler only statically knows 
>> that first & second are of type TypeName, not anything about which case 
>> (they could be passed in as function parameters, or returned by an opaque 
>> function e.g. `let x = OtherLibrary.returnsTypeName(); guard unwrap x else { 
>> … }`), and thus the variant to unwrap has to be chosen based only on that 
>> piece of information.
>> 
>> It seems to me that doing this either has to be restricted to enums with an 
>> “obvious” choice for unwrapping, like Optional, or rely on a sort of 
>> forward-looking type inference that Swift doesn’t currently use to deduce 
>> the unwrapped type based on how the value is used later (and I’m not sure 
>> that works in all cases, e.g. what if T == U for the TypeName example).
> 
> It succeeds on any one-item case and fails on any non-item case.

I think he meant this:

enum TypeName { case anycase(T), anothercase(U) }

func foo(instance: TypeName) {
guard unwrap instance else { ... }
}

What type does instance have? 

> 
> -- E
> 
> 
> ___
> 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] Ban the top value in Int/UInt

2016-10-19 Thread Kevin Nattinger via swift-evolution

> On Oct 19, 2016, at 8:13 AM, Guoye Zhang via swift-evolution 
>  wrote:
> 
> 
>> 在 2016年10月19日,07:10,Jeremy Pereira  写道:
>> 
>> 
>>> On 18 Oct 2016, at 19:17, Guoye Zhang via swift-evolution 
>>>  wrote:
>>> 
>>> Currently, Swift Int family and UInt family have compact representations 
>>> that utilize all available values, which is inherited from C. However, it 
>>> is horribly inefficient to implement optional integers. It takes double the 
>>> space to store [Int?] than to store [Int] because of alignment.
>> 
>> Is this a general problem with Swift? Are lots of people complaining that 
>> they are running out of space for their Optional arrays?
>> 
> It's just that a common data type wasting almost half the space seems 
> inefficient. I guess this is also the reason why they didn't adopt optional 
> integers widely in stdlib.

I’ve only needed an array of optionals once, maybe twice. I don’t think arrays 
of optionals are widely used to begin with, and the reason there are few 
optional integers in the stdlib is because the interface is from objc, which 
doesn’t have optionals. I doubt any thought at all was given in designing the 
standard library to the extra space for an optional.

>> 
>>> 
>>> I propose to ban the top value in Int/UInt which is 0x... in hex. Int 
>>> family would lose its smallest value, and UInt family would lose its 
>>> largest value. Top value is reserved for nil in optionals. An additional 
>>> benefit is that negating an Int would never crash.
>> 
>> Well the “top value” for signed ints would have to be 0x8000... not 
>> 0x... which is the representation of -1. The top value for unsigned ints 
>> cannot be banned because unsigned integers are often used as bit fields 
>> either directly or in OptionSets.
>> 
>> Furthermore, how would the semantics of &+ and &- be affected? What about 
>> the performance of those two operators?
>> 
> I was originally going for the symmetry between Int and UInt as in compatible 
> bit patterns. Now that I think of it, UInt is commonly used for bitwise 
> operations, and it doesn't make sense to optimize for "UInt?" which is 
> uncommon. So I agree that 0x80... is better.
> 
> Int performance would surely suffer because of current instruction sets, but 
> Int? would improve.

In my experience, ints are used orders of magnitude more often than optional 
int?s. Why optimize for the rare case?

> 
>>> 
>>> So what do you think? Can we break C compatibility a bit for better Swift 
>>> types?
>> 
>> 
>> Well it’s not just C compatibility, it’s underlying processor compatibility. 
>> And actually, yes, I think C compatibility is vastly more important than 
>> being able to make your [Int?] arrays smaller considering that full 2’s 
>> complement numbers is what the OS calls and libc calls are expecting.
>> 
> Yes, that is also the result Joe said of their previous internal discussion. 
> Anyway, I know this is improbable, and I'm just glad that this possibility is 
> considered.
> 
> - Guoye
> ___
> 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] Ban the top value in Int/UInt

2016-10-18 Thread Kevin Nattinger via swift-evolution
Part of the beauty of how optionals are implemented in Swift is that the 
compiler doesn’t have to do any magic w.r.t. optionals besides a bit of 
syntactic sugar (`T?` -> `Optional`, `if let x` -> `if let case .some(x)`, 
auto-boxing when necessary, etc.). 
- I strongly dislike the idea of special-casing optionals just to save a Byte. 
- Optionals were presented as explicitly removing the need for such a sentinel 
value in the first place.
- There are reasonable cases where such a bit pattern is reasonably necessary 
to the data (e.g. bit fields, RSSI, IP addresses, etc.) and removing that value 
would force ugly workarounds and/or moving to a larger int size because of an 
ill-advised implementation detail.
- If performance or memory is so critical to your specific use case, use a 
non-optional and your own sentinel value. It’s likely no less efficient than 
having the compiler do it that way.

(more below)

> On Oct 18, 2016, at 11:17 AM, Guoye Zhang via swift-evolution 
>  wrote:
> 
> Currently, Swift Int family and UInt family have compact representations that 
> utilize all available values, which is inherited from C. However, it is 
> horribly inefficient to implement optional integers. It takes double the 
> space to store [Int?] than to store [Int] because of alignment.
> 
> I propose to ban the top value in Int/UInt which is 0x... in hex. Int 
> family would lose its smallest value, and UInt family would lose its largest 
> value. Top value is reserved for nil in optionals. An additional benefit is 
> that negating an Int would never crash.
> 
> Interacting with C/Obj-C is a major concern, but since we are already 
> importing some of the unsigned integers as Int which loses half the values,

I’d argue those imports are bugs and should be fixed to the correct signedness.

> one value is not such big a drawback.

Unless you happen to need all $width bits.

> Alternatively, we could leave current behavior as CInt/CUInt. Converting them 
> to the new Int?/UInt? doesn't generate any instructions since the invalid 
> value already represents nil.

Trying to convert an invalid value like that crashes in most of Swift.

> 
> With optional integers improved, we could implement safe arithmetic 
> efficiently, or even revisit lenient subscript proposals,

I don’t see how losing a particular value has any effect on either of those, 
but it’s possible there’s some theory or implementation detail I’m not aware of.

> but they are not in the scope of this pitch. Float/Double optionals could 
> also be improved with the similar idea. (Isn't signaling nan the same as nil) 
> Nested optionals such as "Int??" are still bloated, but I don't think they 
> are widely used.
> 
> So what do you think? Can we break C compatibility a bit for better Swift 
> types?

We can, and do. C.f. structs, non-@objc classes, and enums not RawRepresentable 
with a C-compatible entity. If anything, this breaks compatibility with the 
rest of Swift.

> 
> - Guoye
> ___
> 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] [Proposal] Enums with stored properties

2016-10-12 Thread Kevin Nattinger via swift-evolution

> On Oct 12, 2016, at 12:25 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
> 
>> On Oct 12, 2016, at 12:32 PM, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>> or more like a body (some different options for syntax, pick one obviously):
>> enum Size {
>>  let height: Int
>>  let width: Int
>>  case small {
>>  height = 30
>>  width = 30
>>  }
>>  case medium: {
>>  .height = 60
>>  .width = 60
>>  }
>>  case large = {
>>  let height = 120
>>  let width = 120
>>  }
>> }
> 
> I sort of prefer to have a protocol-like syntax for declaring the properties, 
> instead of let, because we’re doing something similar to what protocols do: 
> we’re promising that each of these things will provide the property, although 
> they might do it in different ways. This also avoids the connotation we have 
> with “let” that the property will be a constant, when in actuality it may be 
> dynamically computed and thus there is the possibility for it to be different 
> each time.

My expectation is that the stored properties *are* constants, maybe even 
compile-time, though I’m open to runtime-initialized options. The whole point 
of the stored properties (as far as I’m concerned) is that they vary between 
cases but are always the same for a particular case, similar to int- or 
string-backed enums. If there’s a truly variable property, it should not be 
part of whatever associated storage backs the cases.

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


Re: [swift-evolution] [Proposal] Enums with stored properties

2016-10-12 Thread Kevin Nattinger via swift-evolution
As long as I can use the syntax in Braeden's example, I don't really care how 
it's implemented, as sugar for some ugly getters or actual stored values. 


> On Oct 12, 2016, at 04:52, Rien via swift-evolution 
>  wrote:
> 
> I read Braeden’s example such that this proposal is in reality “just” 
> syntactic sugar. AFAIAC it does not change how enums are implemented after 
> compilation.
> 
> Like sugar, it makes working with enums clearer and therefore easier. All 
> initialisation values are defined right there with the ‘case’ instead of 
> hidden in a tree of multiple ‘var’s.
> While I was sceptical about this proposal, Braeden’s example makes it a +1.
> 
> Rien.
> 
> Btw: I made the almost identical suggestion you did ;-)
> 
> 
>> On 12 Oct 2016, at 13:31, Karl  wrote:
>> 
>> I very much disagree with the proposal, and all of the things supporting it 
>> (like deriving enums from other types and whatnot). I think you need to take 
>> a step up from caring about whether it’s a struct or enum and think about 
>> what you are trying to model; that will guide you towards the correct 
>> type(s) to use.
>> 
>> You have only shown a handful of fixed size values, so I would suggest a 
>> computed property in your case:
>> 
>> enum FixedSize {
>> case small
>> case medium
>> case large
>> 
>> struct Size { let width : Int; let height: Int }
>> 
>> var size : Size {
>>   switch self {
>>   case .small: return Size(width: 30, height: 30)
>>   // … etc
>>   }
>> }
>> }
>> 
>> There is no need for these sizes to be stored at all. If you want them baked 
>> in to your enum’s values, clearly you expect them to be specific values. 
>> It’s more efficient to just drop the stored data altogether in this case; 
>> this enum will get lowered in to single byte, which is more efficient to 
>> store and transport.
>> 
>> Karl
>> 
 On 12 Oct 2016, at 13:15, Mateusz Malczak via swift-evolution 
  wrote:
 
 Mateusz, you lost me with “store some extra data”.
 Does that mean something extra besides the code that Braeden suggested?
>>> 
>>> What I meant by “store some extra data” was, to be able to define
>>> immutable properties of any type, as a part of enum instead of
>>> defining getters witch switches. I think Braeden example explains the
>>> whole idea of that proposal.
>>> 
>>> --
>>> | Mateusz Malczak
>>> 
>>> 
>>> 2016-10-12 8:42 GMT+02:00 Rien :
 I’d give a +1 for the suggestion of Braeden.
 
 Mateusz, you lost me with “store some extra data”.
 Does that mean something extra besides the code that Braeden suggested?
 
 Rien.
 
> On 12 Oct 2016, at 00:13, Mateusz Malczak via swift-evolution 
>  wrote:
> 
> That's exactly what this proposal is about. I would like to
> keep all enum properties but add an extra feature, so that enums can
> store some extra data.
> --
> | Mateusz Malczak
> +---
> | mate...@malczak.info
> | http://malczak.info
> 
> 
> 2016-10-11 23:42 GMT+02:00 Braeden Profile :
>> So, just to recap, the proposed solution is to help enums expose 
>> associated
>> values via properties, and is not to create enums that are open to extra
>> unnamed cases (RectSize(width:0,height:10))?  What I see is that enums 
>> would
>> still maintain their standing where an instance is just a selection of a
>> finite number of options, possibly with data attached.  In proposal 1, we
>> want some sort of syntax where this…
>> 
>> enum RectSize
>> {
>> let height:Int
>> let width:Int
>> case small(width: 30, height: 30)
>> case medium(width: 60, height: 60)
>> case large(width: 120, height: 120)
>> }
>> 
>> …is syntactically just like writing this…
>> 
>> enum RectSize
>> {
>> case small
>> case medium
>> case large
>> var height:Int
>> {
>>   switch self
>>   {
>>  case .small: return 30
>>  case .medium: return 60
>>  case .large: return 90
>>   }
>> }
>> let width:Int
>> {
>>   switch self
>>   {
>>  case .small: return 30
>>  case .medium: return 60
>>  case .large: return 90
>>   }
>> }
>> }
>> 
>> …right?  That way, you can write this:
>> 
>> var size: RectSize = .small
>> size.height == 30 // true
>> size.rawValue // Error:  RectSizes has no property `rawValue`.
>> size.height = 40 // Error:  `height` is immutable
>> size = .medium
>> 
>> I think we were also (separately) proposing to extend `rawValue` to take 
>> all
>> kinds of statically known values, like structs or tuples.  Doing that 
>> would
>> accomplish much of the same thing.
>> 
>> Someone fact-check me here!  I really 

Re: [swift-evolution] [Proposal] Enums with stored properties

2016-10-10 Thread Kevin Nattinger via swift-evolution
I would be amenable to that IF we can skip the `.rawValue`, which is, IMO, ugly 
and repetitive.
> On Oct 10, 2016, at 11:54 AM, J.E. Schotsman via swift-evolution 
>  wrote:
> 
> 
>> On 10 Oct 2016, at 15:46,Mateusz Malczak wrote:
>> 
>> t a good illustration of what I would like to be able to define with
>> my proposed feature.
>> But instead to creating a class/struct to in switch case I would like
>> enumeration type to be able to carry that information within its cases
> 
> Wouldn’t it be more natural to allow structs as raw values?
> 
> For example
> 
> struct MyRect
>   {
>   var height:Int
>   var width:Int
>   var area:Int {return height:Int*width}
>   }
> 
> enum RectSizes: MyRect
>   {
>   case Small(30,30)
>   case Medium(60,60)
>   case Large(120,120)
>   }
> 
> let smallArea = RectSizes.Small.rawValue.area
> 
> Jan E.
> ___
> 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] [Proposal] Enums with stored properties

2016-10-10 Thread Kevin Nattinger via swift-evolution
Also, just to be clear, (unfortunately) the enum ship has sailed and I don’t 
think we’ll get a rename/split to union, it’s just that the functionality of 
associated objects is conceptually closer to what other languages call a union. 
 I would, however, like the ability to use an enum in the proper way, as a set 
of compile-time-constant data accessed in an easier way than having to use the 
ugly but currently necessary hack of `switch value { case .x: return 1; case 
.y: return 2; … }`.

> On Oct 10, 2016, at 11:52 AM, Kevin Nattinger <sw...@nattinger.net> wrote:
> 
> 
>> On Oct 10, 2016, at 11:30 AM, Robert Widmann <devteam.cod...@gmail.com 
>> <mailto:devteam.cod...@gmail.com>> wrote:
>> 
>> By imposing that kind of separation you leave an entire class of generic and 
>> structural programming patterns off the table.  An enumeration is not just 
>> an enumeration of constants, it is an enumeration of data, and data takes 
>> far more useful forms than just bitfields
> 
> I’m not sure where you got “bitfields” from, perhaps I was unclear. I think 
> enums should be a set of cases, each case having its distinct and constant 
> set of data with the same structure. If one entity needs data of different, 
> dynamic structure and value at runtime, that is essentially the definition of 
> a union.
> 
>> - similarly when it does have that form it fits precisely into the form of 
>> an enum with no cases?  Why artificially separate the two concepts when 
>> they’re clearly one and the same?
>> 
>> ~Robert Widmann
>> 
>>> On Oct 10, 2016, at 2:24 PM, Kevin Nattinger via swift-evolution 
>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> I agree wholeheartedly. An enum case should be a compile-time constant.  
>>> IMO, “enums” with associated values should properly be a separate entity, 
>>> called “union” as that’s essentially what they are. 
>>> 
>>>> On Oct 10, 2016, at 10:31 AM, Kenny Leung via swift-evolution 
>>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>>> 
>>>> This is the way Java enumerations work. 
>>>> 
>>>> https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 
>>>> <https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html>
>>>> 
>>>> I think it is a good model, and I think Swift enumerations should also 
>>>> work the same way.
>>>> 
>>>> An enumeration is a finite set of things. It’s really inconvenient to have 
>>>> to limit those things to have only a single attribute.
>>>> 
>>>> -Kenny
>>>> 
>>>> 
>>>> ___
>>>> swift-evolution mailing list
>>>> swift-evolution@swift.org <mailto:swift-evolution@swift.org>
>>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>> 
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org <mailto:swift-evolution@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>>> <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] [Proposal] Enums with stored properties

2016-10-10 Thread Kevin Nattinger via swift-evolution

> On Oct 10, 2016, at 11:30 AM, Robert Widmann <devteam.cod...@gmail.com> wrote:
> 
> By imposing that kind of separation you leave an entire class of generic and 
> structural programming patterns off the table.  An enumeration is not just an 
> enumeration of constants, it is an enumeration of data, and data takes far 
> more useful forms than just bitfields

I’m not sure where you got “bitfields” from, perhaps I was unclear. I think 
enums should be a set of cases, each case having its distinct and constant set 
of data with the same structure. If one entity needs data of different, dynamic 
structure and value at runtime, that is essentially the definition of a union.

> - similarly when it does have that form it fits precisely into the form of an 
> enum with no cases?  Why artificially separate the two concepts when they’re 
> clearly one and the same?
> 
> ~Robert Widmann
> 
>> On Oct 10, 2016, at 2:24 PM, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>> I agree wholeheartedly. An enum case should be a compile-time constant.  
>> IMO, “enums” with associated values should properly be a separate entity, 
>> called “union” as that’s essentially what they are. 
>> 
>>> On Oct 10, 2016, at 10:31 AM, Kenny Leung via swift-evolution 
>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> This is the way Java enumerations work. 
>>> 
>>> https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 
>>> <https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html>
>>> 
>>> I think it is a good model, and I think Swift enumerations should also work 
>>> the same way.
>>> 
>>> An enumeration is a finite set of things. It’s really inconvenient to have 
>>> to limit those things to have only a single attribute.
>>> 
>>> -Kenny
>>> 
>>> 
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org <mailto: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] [Proposal] Enums with stored properties

2016-10-10 Thread Kevin Nattinger via swift-evolution
I agree wholeheartedly. An enum case should be a compile-time constant.  IMO, 
“enums” with associated values should properly be a separate entity, called 
“union” as that’s essentially what they are. 

> On Oct 10, 2016, at 10:31 AM, Kenny Leung via swift-evolution 
>  wrote:
> 
> This is the way Java enumerations work. 
> 
> https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
> 
> I think it is a good model, and I think Swift enumerations should also work 
> the same way.
> 
> An enumeration is a finite set of things. It’s really inconvenient to have to 
> limit those things to have only a single attribute.
> 
> -Kenny
> 
> 
> ___
> 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] Fwd: Propagating Optionals

2016-10-07 Thread Kevin Nattinger via swift-evolution

> On Oct 7, 2016, at 2:56 PM, Trans via swift-evolution 
>  wrote:
> 
> Just discovered that none of my replies made it to the mailing list.
> Doesn't it bug others that the default reply is to the author and not
> the list?
> 
> 
> -- Forwarded message --
> From: Trans 
> Date: Sun, Sep 25, 2016 at 9:36 PM
> Subject: Re: [swift-evolution] Propagating Optionals
> To: William Sumner 
> 
> 
> On Sun, Sep 25, 2016 at 7:26 PM, William Sumner  wrote:
>> 
>> You can accomplish this using parenthesis:
>> 
>> let roomCount = (john.residence ?? homelessShelter).numberOfRooms
> 
> Yea. Don't know why that escaped me. Though it does start to look long
> in the tooth if there is more than one.
> 
>let x = ((foo.bar ?? dbar).baz ?? dbaz).zee
> 
> vs
> 
>let x = foo.bar:dbar.baz:dbaz.zee

I’m not sure what I’d expect a raw `:` operator to do, but whatever it is I’d 
expect it to have a lower priority than `.`, making your statement equal to

let x = (foo.bar) : (dbar.baz) : (dbaz.zee)

Member access (`.`) is a *very* high precedence operator in every language I 
can think of, and I think it would be quite confusing to slip something in 
above it.

> 
> But then again maybe that is too concise.
> 
> 
> -- 
> People with courage and character always seem sinister to the rest.
> --Hermann Hesse
> 
> Trans 
> 7r4n5.com  http://7r4n5.com
> ___
> 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] Add something like [unowned self] syntax for passing instance methods into closure parameters without creating retain cycles

2016-09-13 Thread Kevin Nattinger via swift-evolution

> On Sep 13, 2016, at 10:29 AM, Benjamin Spratling via swift-evolution 
>  wrote:
> 
> Well, then also add an unowned convenience.
> But I’ve never been handed a story from UX that said, “As a user, when  I 
> want the app to crash.”
> Using weak, the compiler can tell me when I’ve missed a possible case where 
> it’s nil.

Honestly, I’d be fine with / prefer only allowing unowned (at all) if it’s 
@noescape, if that, requiring strong or weak for anything that escapes. That 
seems to go along with swift’s emphasis on safety. 

> But the point here is to get closure references that don’t create retain 
> cycles.  Obviously, there’s desire for both weak and unowned variants without 
> the syntactic overhead of a full closure.
> 
>> On Sep 13, 2016, at 12:22 PM, Karl Wagner > > wrote:
>> 
>> Weak references can have a non-trivial amount of overhead in 
>> high-performance code. In some cases you can guarantee that a pointer should 
>> never be null - and that if it is, a serious logic error has occcurred and 
>> you *should* crash.
>> 
>> I prefer crashing to running in an inconsistent state. Who knows what can 
>> happen in the latter case - data corruption? I'd prefer to crash, get a 
>> report and fix the bug.
>> 
>> Karl
>> 
>> This 
>> 
>>  is how I Email now
>> 
>> 
>>> On Sep 13, 2016 at 11:07 am, >> > wrote:
>>> 
>>> Nick, I like where you’re headed with the instance-methods-as-closures 
>>> idea.  Here’s where I’m headed with it:
>>> 
>>> Closures are too often used to write the contents of what should be another 
>>> function, producing code similar to the “pyramid of doom” avoided by guard. 
>>>  I now generally write as little code as possible in a closure, and use it 
>>> merely to dispatch out to a private function as quickly as possible.  This 
>>> means I really do want classes to reference their own functions.  I look at 
>>> closures more as providing the captured scope as the "void* context" that 
>>> goes along with an old C function reference, as opposed to being the scope 
>>> in which the code should be written.
>>> 
>>> I loved the “get a closure to implicit self using nothing but the function 
>>> name” feature of Swift, but after running over a dead line by spending 1.5 
>>> days with 3 other developers trying to find a retain cycle caused by its 
>>> use, we added it to our list of reasons to not merge code, hereafter 
>>> referred to as “the list".  This from a guy who used to write flawless 
>>> manual retain/release code, back in the day.
>>> 
>>> Incidentally, we also put “unowned" on "the list".  We always use “weak” 
>>> instead.  The bottom line is unowned CAN crash, and weak can’t.  There is 
>>> no way to know if a call to unowned will crash or not.  So we prefer to 
>>> write code that can’t crash. (No, we don’t force-unwrap weak optionals, “!” 
>>> is on "the list”, and we nicknamed it the “Russian Roulette operator”)  So 
>>> instead of “something like [unowned self] syntax...”, I’m suggesting 
>>> “something like [weak self] syntax..."
>>> 
>>> So I’d prefer something like “weakself?.functionName” to produce a closure 
>>> which wraps a weak-self reference and a call to the given method if self 
>>> isn’t nil.  This seems like a trivial task for the compiler when return 
>>> types are Void or Optional.  Given the expectations of optional chaining, 
>>> and the zeroing behavior of any not-owned relationship, I’m not sure it 
>>> makes sense to demand a non-optional return type for a call to a parent.  
>>> So I don’t think such a feature even needs to worry about what if the 
>>> expected return type isn’t optional.
>>> 
>>> I’d be happy to see any of the following syntaxes:
>>> 
>>> weakself.functionName
>>> weakself?.functionName
>>> ?functionName
>>> welf.functionName
>>> self?.functionName
>>> weak(self)?.functionName
>>> 
>>> Obviously, one work around is to declare a protocol, and pass self, letting 
>>> the receiving class store a weak reference.  But declaring protocols for 
>>> every single closure reference is a bit tedious.  Literally just the back 
>>> and forth on naming them is a waste of time.  And there’s the running joke 
>>> that we’d just tack “able” on the end of the method name.
>>> 
>>> Another work around is to create several generic classes which generate 
>>> closures which weakly capture self and an unapplied method reference, and 
>>> overloaded functions or operators to provide the correct class.  
>>> Unfortunately, this still requires writing “self” explicitly, and also 
>>> explicitly writing the type of self to obtain an unapplied method reference.
>>> 
>>> Given our experience, I would consider giving a warning when an 
>>> implicit-self closure goes into an @escaping context.
>>> 
>>> class SomeClass {
>>> var someFunction:(()->())?
>>>

Re: [swift-evolution] Type-annotated throws

2016-08-26 Thread Kevin Nattinger via swift-evolution
+1 from me.  I’m usually highly defensive about types, so the more the compiler 
can guarantee the better. 

> On Aug 26, 2016, at 9:01 AM, Nur Ismail via swift-evolution 
>  wrote:
> 
> Hi,
> 
> Sounds like checked exceptions of Java with a similar syntax. With Java you 
> have to specify the exceptions a method can throw. However been lots of 
> debate over the years whether it's a good thing or bad thing, some like it, 
> but I think many more hate it.

I’m pretty sure what people don’t like in Java is the enforced error handling 
or propagation and how much you have to nest to, e.g. set up IO, though I 
believe that has been mitigated somewhat by try-with-resources), not the 
specificity (and how it’s not obvious to many which throws need to be caught at 
compile time and which are RuntimeExceptions).  Though I don’t write much Java 
nowadays, I know I never liked all the boilerplate that required.

> Most other languages don't have it, and possibly for good reason.

I’d love to hear those arguments against letting the compiler make more 
guarantees.

> 
> Regards,
> 
> On Fri, Aug 26, 2016 at 5:43 PM, Rod Brown via swift-evolution 
> > wrote:
> (resent for Swift Evolution)
> 
> I’m a big fan of this idea. Currently “throws” seems like a very limited API 
> - you know it’s throwing out something, but you can only hope to guess what 
> that is or create fallbacks. Definitely a big +1 from me. A fallback for 
> compatibility could be “throws” assumes “throws Any” and can be a warning?

I’d suggest a bare `throws` = `throws ErrorType` (you can only throw ErrorType, 
right?) and be valid, I don’t see any reason to make it a warning (plus that 
keeps source compatibility). 

> 
> While I am not deeply familiar with the implications, I do like think your 
> line of reasoning has merit, and think this makes sense for Phase 1 of Swift 
> 4. 
> 
> - Rod
> 
> 
>> On 27 Aug 2016, at 1:39 AM, Félix Cloutier via swift-evolution 
>> > wrote:
>> 
>> Hi all,
>> 
>> Currently, a function that throws is assumed to throw anything. There was a 
>> proposal draft last December to restrict that. The general idea was that 
>> you'd write, for instance:
>> 
>>> enum Foo: ErrorProtocol {
>>> case bar
>>> case baz
>>> }
>>> 
>>> func frob() throws Foo {
>>> throw Foo.bar // throw .bar?
>>> }
>> 
>> If you `catch Foo` (or every case of Foo), now that the compiler can verify 
>> that your catch is exhaustive, you no longer have to have a catch-all block 
>> at the end of the sequence.
>> 
>> This impacts the metadata format and has implications on resilience, which 
>> leads me to believe that the discussion could qualify for the phase 1 of 
>> Swift 4. If this is the case, I'd be interested in pulling out the old 
>> discussions and seeing where we left that at.
>> 
>> Félix
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] Change Request: Make myString.hasPrefix("") and myString.hasSuffix("") return true

2016-07-18 Thread Kevin Nattinger via swift-evolution
I agree, true is definitely the expected behavior. In particular, it seems 
absurd to me that `a.hasPrefix(b)` and `a.hasSuffix(b)` could be false when `a 
== b` is true.

> On Jul 18, 2016, at 10:36 AM, Chris Denter via swift-evolution 
>  wrote:
> 
> Hello –
> 
> Currently, the standard library String functions .hasPrefix() and 
> .hasSuffix() will return false when given the empty string as input:
> 
> $ swift
>   1> "".hasPrefix("")
> $R0: Bool = false
>   2> "foo".hasPrefix("") 
> $R1: Bool = false
>   3> "foo".hasSuffix("")
> $R2: Bool = false
> 
> 
> This feels unexpected. The reason the methods behave this way seems to be a 
> leaked implementation detail.
> Some languages, such as Python, return True in these cases -- perhaps 
> motivated by the `someSet.contains(emptySet) == true` analogy.
> 
> The ship has sailed for NSString and Foundation, but we might want to bite 
> the bullet and fix this for Swift before 3.0 makes that much harder.
> 
> Thank you so much for your time,
> 
> Chris
> ___
> 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] Extending declaration scope to condition for `repeat { } while ()`

2016-07-18 Thread Kevin Nattinger via swift-evolution
I would love this behavior, I ran into a case just a week or two ago where I 
was wishing for this behavior.

That said, I’m not sure whether it would be possible / feasible for the 
compiler. And it’s additive so it will have to wait for after Swift 3 is 
released.

> On Jul 18, 2016, at 10:52 AM, Braeden Profile via swift-evolution 
>  wrote:
> 
> Good morning, Swift community!
> 
> I’ve come across a situation a number of times where I write code that has to 
> try something one or more times using a `repeat…while` loop and the condition 
> relies upon variables that should be declared within the scope of the loop.
> 
> repeat
> {
>   let success = doSomething()
> }
> while !success
> 
> The compiler unnecessarily prohibits this:  “Use of unresolved identifier 
> four.”  In this simple case, we can write:
> 
> repeat
> { }
> while !doSomething()
> 
> But in a more complex situation, we are forced to write:
> 
> var success: Bool
> repeat
> {
>   success = doSomething()
> }
> while !success
> 
> 
> We could change this so that the declarations within the top level scope of 
> the loop are accessible from the condition.
> 
> Thanks for reading my first post to the Swift discussion board!
> —Braeden
> ___
> 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] Remove type inference for associated types

2016-06-30 Thread Kevin Nattinger via swift-evolution

> On Jun 30, 2016, at 10:28 AM, Douglas Gregor via swift-evolution 
>  wrote:
> 
>> 
>> On Jun 30, 2016, at 9:55 AM, David Hart via swift-evolution 
>>  wrote:
>> 
>> I don't see that as confusing. In a conforming type, he compiler is looking 
>> for a type with the same name as the associatedtype declaration. As the 
>> proposal mentions, typealias is not the only way to provide that type. It's 
>> actually logical to typealias to point the compiler to the correct type as 
>> well as it is to define a internal type with the same name from the start.
> 
> “associatedtype” used to be “typealias”, because we were trying to make the 
> declaration in the protocol use the same spelling as the common case for 
> conforming types, which turned out to be a bad idea. Hence, SE-0011:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0011-replace-typealias-associated.md

Why didn’t we just go with generics? That’s essentially what it is.

> 
>   - Doug
> 
> 
>> 
>>> On 30 Jun 2016, at 15:22, Brandon Knope via swift-evolution 
>>>  wrote:
>>> 
>>> But surely using two different keywords could seem confusing to many as 
>>> part of the same system?
>>> 
>>> Using associatedtype in the declaration and then typealias in the 
>>> conforming type just seems inconsistent and ripe for confusion. '
>>> 
>>> I am curious if any advanced Swift users still get tripped up here
>>> 
>>> Brandon 
>>> 
>>> Sent from my iPad
>>> 
>>> On Jun 30, 2016, at 8:53 AM, Brent Royal-Gordon  
>>> wrote:
>>> 
> On Jun 29, 2016, at 6:55 AM, Brandon Knope via swift-evolution 
>  wrote:
> 
> What's the rationale for having associatedtype in protocols and typealias 
> in the conforming types?
 
 I didn't design it, but here's how I think about it: The associated type 
 requirement merely states that there must be a type with this name meeting 
 these criteria. `typealias` is one way to satisfy that requirement, but 
 you can also just define a nested type with that name:
 
 struct MyCollection {
 struct Index: Comparable { … }
 }
 
 Should you replace `struct` with `associatedtype`? No? Then why would you 
 replace `typealias` with `associatedtype`?
 
 -- 
 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
> 
> ___
> 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] Optionals and nil in Switch statement

2016-06-28 Thread Kevin Nattinger via swift-evolution
Slight amendment for `let` case, which does evidently still require the 
explicit `.some`

switch str {
case "foo": print("foo")
case .some(let string): print(string) // `case let .some(string)` also works
case nil: print("nil")
}

> On Jun 28, 2016, at 11:10 AM, Kevin Nattinger via swift-evolution 
> <swift-evolution@swift.org> wrote:
> 
> I’ve always thought it’s a bit odd, but that’s the way it is. FWIW, if you 
> define `T? ~= T?` (switch uses `~=` under the hood), you can use that syntax:
> 
> public func ~=(a: T?, b: T?) -> Bool {
>   return a == b
> }
> 
> switch str {
> case "foo": print("foo")
> case "bar": print("bar")
> case nil: print("nil")
> default: print("other")
> }
> 
> For better or worse, this prevents you from using the `.some(x)` / `.none` 
> version.
> 
> You could propose adding this to the standard library to the swift-evolution 
> list, see how they react.
> 
>> On Jun 28, 2016, at 9:52 AM, Lucas Jordan <lucasjor...@gmail.com> wrote:
>> 
>> This is sort of weird right? because comparing nil to a non nil string is a 
>> reasonable thing to do:
>> 
>> var nilString:String? = nil
>> 
>> if nilString == "this always fails" {}
>> 
>> is totally reasonable.
>> 
>> On Tue, Jun 28, 2016 at 12:33 PM, Kevin Nattinger <sw...@nattinger.net> 
>> wrote:
>> No
>> 
>>   7> switch str {
>>   8. case "foo": print("case foo")
>>   9. case .none: print("(nil)")
>>  10. }
>> error: repl.swift:8:6: error: value of optional type 'String?' not 
>> unwrapped; did you mean to use '!' or '?'?
>> case "foo": print("case foo")
>>  ^
>>   !
>> Odd error, but at least it suggests it’s an issue with optionaity.
>> 
>> 
>>> On Jun 28, 2016, at 9:27 AM, Nevin Brackett-Rozinsky 
>>> <nevin.brackettrozin...@gmail.com> wrote:
>>> 
>>> Does `case "text"?` work?
>>> 
>>> 
>>> On Tuesday, June 28, 2016, Kevin Nattinger via swift-evolution 
>>> <swift-evolution@swift.org> wrote:
>>> Case .none:
>>> Case .some("string"):
>>> 
>>> 
>>> On Jun 28, 2016, at 06:40, Lucas Jordan via swift-evolution 
>>> <swift-evolution@swift.org> wrote:
>>> 
>>>> Forgive me if this was/is discussed already, I am new to the process 
>>>> here
>>>> 
>>>> (code is attached as a playground too)
>>>> 
>>>> 
>>>> 
>>>> Sometimes when I am working with a String? nil can be a reasonable value, 
>>>> and what I want to do is something like the following:
>>>> 
>>>> import UIKit
>>>> 
>>>> 
>>>> 
>>>> var str:String? = "Hello, playground"
>>>> 
>>>> 
>>>> 
>>>> switch str{
>>>> 
>>>> case nil:
>>>> 
>>>> print("Nil!")
>>>> 
>>>> case "Hello, playground":  //it would be super nice if this worked.
>>>> 
>>>> print("Match")
>>>> 
>>>> default:
>>>> 
>>>> print("Some other non nil value?")
>>>> 
>>>> }
>>>> 
>>>> 
>>>> 
>>>> But it does not work, the orange  text is a compile time error, 
>>>> "Expression pattern of type 'String' cannot match value of type 'String?'. 
>>>> I realize that this can be replaced with a let statement (case let s where 
>>>> s == "Hello, playground":), but that is verbose. 
>>>> 
>>>> Seems like the compiler could be OK with the orange text, since it is 
>>>> clearly not nil.
>>>> 
>>>> Thoughts?
>>>> 
>>>> -Lucas
>>>> 
>>>> 
>>>> 
>>>> 
>>>> 
>>>> 
>>>> ___
>>>> 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] Optionals and nil in Switch statement

2016-06-28 Thread Kevin Nattinger via swift-evolution
I’ve always thought it’s a bit odd, but that’s the way it is. FWIW, if you 
define `T? ~= T?` (switch uses `~=` under the hood), you can use that syntax:

public func ~=(a: T?, b: T?) -> Bool {
return a == b
}

switch str {
case "foo": print("foo")
case "bar": print("bar")
case nil: print("nil")
default: print("other")
}

For better or worse, this prevents you from using the `.some(x)` / `.none` 
version.

You could propose adding this to the standard library to the swift-evolution 
list, see how they react.

> On Jun 28, 2016, at 9:52 AM, Lucas Jordan <lucasjor...@gmail.com> wrote:
> 
> This is sort of weird right? because comparing nil to a non nil string is a 
> reasonable thing to do:
> 
> var nilString:String? = nil
> 
> if nilString == "this always fails" {}
> 
> is totally reasonable.
> 
> On Tue, Jun 28, 2016 at 12:33 PM, Kevin Nattinger <sw...@nattinger.net> wrote:
> No
> 
>   7> switch str {
>   8. case "foo": print("case foo")
>   9. case .none: print("(nil)")
>  10. }
> error: repl.swift:8:6: error: value of optional type 'String?' not unwrapped; 
> did you mean to use '!' or '?'?
> case "foo": print("case foo")
>  ^
>   !
> Odd error, but at least it suggests it’s an issue with optionaity.
> 
> 
>> On Jun 28, 2016, at 9:27 AM, Nevin Brackett-Rozinsky 
>> <nevin.brackettrozin...@gmail.com> wrote:
>> 
>> Does `case "text"?` work?
>> 
>> 
>> On Tuesday, June 28, 2016, Kevin Nattinger via swift-evolution 
>> <swift-evolution@swift.org> wrote:
>> Case .none:
>> Case .some("string"):
>> 
>> 
>> On Jun 28, 2016, at 06:40, Lucas Jordan via swift-evolution 
>> <swift-evolution@swift.org> wrote:
>> 
>>> Forgive me if this was/is discussed already, I am new to the process 
>>> here
>>> 
>>> (code is attached as a playground too)
>>> 
>>> 
>>> 
>>> Sometimes when I am working with a String? nil can be a reasonable value, 
>>> and what I want to do is something like the following:
>>> 
>>> import UIKit
>>> 
>>> 
>>> 
>>> var str:String? = "Hello, playground"
>>> 
>>> 
>>> 
>>> switch str{
>>> 
>>> case nil:
>>> 
>>> print("Nil!")
>>> 
>>> case "Hello, playground":  //it would be super nice if this worked.
>>> 
>>> print("Match")
>>> 
>>> default:
>>> 
>>> print("Some other non nil value?")
>>> 
>>> }
>>> 
>>> 
>>> 
>>> But it does not work, the orange  text is a compile time error, "Expression 
>>> pattern of type 'String' cannot match value of type 'String?'. I realize 
>>> that this can be replaced with a let statement (case let s where s == 
>>> "Hello, playground":), but that is verbose. 
>>> 
>>> Seems like the compiler could be OK with the orange text, since it is 
>>> clearly not nil.
>>> 
>>> Thoughts?
>>> 
>>> -Lucas
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> ___
>>> 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] Optionals and nil in Switch statement

2016-06-28 Thread Kevin Nattinger via swift-evolution
No

  7> switch str {
  8. case "foo": print("case foo")
  9. case .none: print("(nil)")
 10. }
error: repl.swift:8:6: error: value of optional type 'String?' not unwrapped; 
did you mean to use '!' or '?'?
case "foo": print("case foo")
 ^
  !
Odd error, but at least it suggests it’s an issue with optionaity.

> On Jun 28, 2016, at 9:27 AM, Nevin Brackett-Rozinsky 
> <nevin.brackettrozin...@gmail.com> wrote:
> 
> Does `case "text"?` work?
> 
> 
> On Tuesday, June 28, 2016, Kevin Nattinger via swift-evolution 
> <swift-evolution@swift.org> wrote:
> Case .none:
> Case .some("string"):
> 
> 
> On Jun 28, 2016, at 06:40, Lucas Jordan via swift-evolution 
> <swift-evolution@swift.org> wrote:
> 
>> Forgive me if this was/is discussed already, I am new to the process here
>> 
>> (code is attached as a playground too)
>> 
>> 
>> 
>> Sometimes when I am working with a String? nil can be a reasonable value, 
>> and what I want to do is something like the following:
>> 
>> import UIKit
>> 
>> 
>> 
>> var str:String? = "Hello, playground"
>> 
>> 
>> 
>> switch str{
>> 
>> case nil:
>> 
>> print("Nil!")
>> 
>> case "Hello, playground":  //it would be super nice if this worked.
>> 
>> print("Match")
>> 
>> default:
>> 
>> print("Some other non nil value?")
>> 
>> }
>> 
>> 
>> 
>> But it does not work, the orange  text is a compile time error, "Expression 
>> pattern of type 'String' cannot match value of type 'String?'. I realize 
>> that this can be replaced with a let statement (case let s where s == 
>> "Hello, playground":), but that is verbose. 
>> 
>> Seems like the compiler could be OK with the orange text, since it is 
>> clearly not nil.
>> 
>> Thoughts?
>> 
>> -Lucas
>> 
>> 
>> 
>> 
>> 
>> 
>> ___
>> 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] Optionals and nil in Switch statement

2016-06-28 Thread Kevin Nattinger via swift-evolution
Case .none:
Case .some("string"):


> On Jun 28, 2016, at 06:40, Lucas Jordan via swift-evolution 
>  wrote:
> 
> Forgive me if this was/is discussed already, I am new to the process here
> 
> (code is attached as a playground too)
> 
> 
> 
> Sometimes when I am working with a String? nil can be a reasonable value, and 
> what I want to do is something like the following:
> 
> import UIKit
> 
> 
> 
> var str:String? = "Hello, playground"
> 
> 
> 
> switch str{
> 
> case nil:
> 
> print("Nil!")
> 
> case "Hello, playground":  //it would be super nice if this worked.
> 
> print("Match")
> 
> default:
> 
> print("Some other non nil value?")
> 
> }
> 
> 
> 
> But it does not work, the orange  text is a compile time error, "Expression 
> pattern of type 'String' cannot match value of type 'String?'. I realize that 
> this can be replaced with a let statement (case let s where s == "Hello, 
> playground":), but that is verbose. 
> 
> Seems like the compiler could be OK with the orange text, since it is clearly 
> not nil.
> 
> Thoughts?
> 
> -Lucas
> 
> 
> 
> 
> 
> 
> ___
> 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-0102: Remove @noreturn attribute and introduce an empty NoReturn type

2016-06-21 Thread Kevin Nattinger via swift-evolution

> On Jun 21, 2016, at 10:03 AM, Chris Lattner via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of "SE-0102: Remove @noreturn attribute and introduce an empty 
> NoReturn type" begins now and runs through June 27. The proposal is available 
> here:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0102-noreturn-bottom-type.md
> 
> Reviews are an important part of the Swift evolution process. All reviews 
> should be sent to the swift-evolution mailing list at
> 
>   https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> or, if you would like to keep your feedback private, directly to the review 
> manager.
> 
> What goes into a review?
> 
> The goal of the review process is to improve the proposal under review 
> through constructive criticism and contribute to 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. 
noreturn is logically and fundamentally an attribute of a function, not a 
return (pseudo-)type, and it should continue to be expressed that way. 
If the idea of `@noreturn foo() -> Int` being valid really bothers you so much, 
just forbid functions declared noreturn from having a specified return type 
(maybe even an explicit `()`/`Void`).


>   * Is the problem being addressed significant enough to warrant a change 
> to Swift?

No.
There is no problem being solved. noreturn as an attribute is clear, 
precedented, and easily searchable. Furthermore, I feel the proposal doesn’t 
even fix most of the “issues” it brings up in the motivation section— `-> 
NoReturn throws` is no more clear than `@noreturn throws`, and `compose(exit, 
getExitCode)` is no more clear declared `-> NoReturn` than `@noreturn`.  And it 
introduces ambiguity of its own. If someone defines their own empty enum, does 
`func foo() -> MyEmptyEnum` get the same treatment as NoReturn? If not, why is 
it special cased? If so, 

>   * Does this proposal fit well with the feel and direction of Swift?

No.
We want swift to be intuitive. IMO, `@noreturn` is way more intuitive than 
saying you’ll return something that you can’t actually follow through with. And 
 everywhere else such a contradiction would be a compiler error. 

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

It unnecessarily breaks from tradition. The C family uses noreturn attributes. 
I haven’t seen anyone bring up language where noreturn is achieved in this 
manner.

>   * How much effort did you put into your review? A glance, a quick 
> reading, or an in-depth study?

Followed the email chain, thoroughly read the proposal.

> 
> More information about the Swift evolution process is available at
> 
>   https://github.com/apple/swift-evolution/blob/master/process.md
> 
> Thank you,
> 
> -Chris Lattner
> 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] [Draft] Change @noreturn to unconstructible return type

2016-06-07 Thread Kevin Nattinger via swift-evolution

> On Jun 7, 2016, at 12:49 PM, Michael Peternell via swift-evolution 
>  wrote:
> 
>> 
>> Am 07.06.2016 um 19:45 schrieb Charles Srstka via swift-evolution 
>> :
>> 
>>> On Jun 7, 2016, at 11:47 AM, Brent Royal-Gordon via swift-evolution 
>>>  wrote:
>>> 
 I disagree. We are discussing how to annotate a function in some way so 
 that the compiler knows that the code following it will never be executed 
 *and* so a human who reads the declaration knows that it does not return. 
 “Never" is a poor choice for that. Never what? Never return? Never use 
 this function? Never say never again? 
>>> 
>>> "Never return". That's why it's in the return type slot, right after the 
>>> `->`. If you read it out loud, you'll read "returns Never", which is 
>>> exactly correct.
>>> 
>>> NoReturn, on the other hand, does *not* read well in that slot: "returns 
>>> NoReturn". Huh? I mean, I suppose you won't misunderstand it, but it makes 
>>> no sense whatsoever *as a type name*.
>> 
>> But it’s *not* a type. You’ll never have an instance of it. Since it’s not a 
>> type name, it doesn’t make sense that it needs to look like one. What it is 
>> doing is telling you something about the behavior of the function itself, 
>> not its return value. Its return value, if there were one, is irrelevant, 
>> since the function, by its very nature, will never even get to the point 
>> where it would return it. Either it’s going to kill the app via a fatalError 
>> or something, or we have something like dispatch_main() which will keep 
>> executing until the program stops, and one way or another, it won’t return.
>> 
>> For that reason, frankly, I don’t understand why we want to change this from 
>> being an attribute, which seems to me the more natural and logical choice to 
>> describe this behavior. If we *do* have to change it, though, NoReturn 
>> conveys the most clearly to the reader what it does.
> 
> +1 for @noreturn
> We don't have to change it.
> We have to keep it.

+1 from me too. 
Logically, “does not return" is an annotation: the function doesn’t return 
something that can’t be returned, it just doesn’t resume execution at the call 
point. 

> 
> -Michael
> 
>> 
>> Charles
>> 
>> ___
>> 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] Ad hoc enums / options

2016-05-31 Thread Kevin Nattinger via swift-evolution
Definitely an interesting idea, and I like it, but how would this be used from 
Objective C? 
> On May 31, 2016, at 9:16 AM, Erica Sadun via swift-evolution 
>  wrote:
> 
> Here's a function signature from some code from today:
> 
> func scaleAndCropImage(
> image: UIImage,
> toSize size: CGSize,
> fitImage: Bool = true
> ) -> UIImage {
> 
> 
> And here's what I want the function signature to actually look like:
> 
> func scaleAndCropImage(
> image: UIImage,
> toSize size: CGSize,
> operation: (.Fit | .Fill) = .Fit
> ) -> UIImage {
> 
> 
> where I don't have to establish a separate enumeration to include ad-hoc 
> enumeration-like semantics for the call. A while back, Yong hee Lee 
> introduced anonymous enumerations (and the possibility of anonymous option 
> flags) but the discussion rather died.
> 
> I'm bringing it up again to see whether there is any general interest in 
> pursuing this further as I think the second example is more readable, 
> appropriate, and Swifty than the first, provides better semantics, and is 
> more self documenting.
> 
> Thanks for your feedback,
> 
> -- Erica
> 
> ___
> 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] [Idea] Switch Statement with Optional Binding

2016-05-27 Thread Kevin Nattinger via swift-evolution
You can do it today (2.2 and 3.0-master) like this:

switch cityIDs["Paris"] {
case let .Some(parisCityID) where 0..<10 ~= parisCityID:
print("Paris city ID: \(parisCityID)")
default:
break
}

> On May 27, 2016, at 1:58 AM, Natthan Leong via swift-evolution 
>  wrote:
> 
> Hi there,
> 
> I was wondering if the community would like Swift to have a switch statement 
> with optional binding.
> 
> Take this simple dictionary as an example:
> 
> let cityIDs = ["Paris": 1, "London": 2]
> 
> Currently, this is how things are done if parisCityID is used only once 
> within an if-let statement for only a switch statement: 
> 
> if let parisCityID = cityIDs["Paris"] {
> switch parisCityID {
> case 0..<10:
> print("Paris city ID: \(parisCityID)")
> default:
> break
> }
> }
> 
> And here is the proposed switch statement with optional binding:
> 
> switch let parisCityID = cityIDs["Paris"] {
> case 0..<10:
> print("Paris city ID: \(parisCityID)")
> default:
> break
> }
> 
> With var:
> 
> switch var parisCityID = cityIDs["Paris"] {
> case 0..<10:
> parisCityID += 2 // just to demonstrate var
> print("Paris city ID: \(parisCityID)")
> default:
> break
> }
> 
> Feedback welcomed!
> ___
> 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] Proposal: Automatic initializer generation

2016-05-23 Thread Kevin Nattinger via swift-evolution
Discussed last month 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160411/014890.html
And (linked from that thread) last year 
http://article.gmane.org/gmane.comp.lang.swift.evolution/727

I think it’s a good idea, but discussion seems to have just petered out without 
a formal proposal both times. 

How about we just apply the struct auto-init behavior to classes? It’s nice and 
simple, and already in the language.

> On May 23, 2016, at 7:29 AM, Charlie Monroe via swift-evolution 
>  wrote:
> 
> A lot of initializers tediously assign values to variables which results in a 
> lot of code such as self.variable = arg1 (or even worse variable = variable), 
> mostly for classes that are meant to just encapsulate several values.
> 
> I propose adding auto keyword (to be discussed - anyone has a better name in 
> mind?), which would automatically assign same-named variables. Example:
> 
> class User {
>   var name: String
>   var password: String
>   
>   init(auto name: String, auto password: String) {
>   // No assignment required, the variables will be automatically 
> assigned.
>   // Perform additional init stuff here.
>   }
> }
> 
> This would, of course, work only if the argument has the same name as a 
> stored variable on the class.
> 
> Additionally, if the class is root, or the superclass has an initializer that 
> takes no arguments, I propose adding @auto_init annotation, which would 
> generate a default initializer, similar to what is done for structs:
> 
> @auto_init
> class User {
>   var name: String
>   var password: String
> }
> 
> Normally, such class would be illegal since it would have no accessible 
> initializers. The annotation could specify the access control as well: 
> @auto_init(private), @auto_init(internal), @auto_init(public).
> 
> If the class isn't root, but inherits from an object that has an initializer 
> that takes no arguments (e.g. NSObject), this would be allowed as well and 
> the initializer with no arguments would be called on super.
> 
> Any thoughts on this? Sorry, if this has been already discussed.
> 
> Charlie
> 
> ___
> 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