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

2017-10-14 Thread Karim Nassar via swift-evolution

This matches with my first-read gut-interpretation as well. Even though this 
might be technically an accurate use of the word, when I read 
“lexicographically” that implies to me a “natural ordering of the elements", 
not whatever the ordering happens to be on the collection at that time, so that 
I would expect:

[“A”, “B”, “C”].lexographicallyEquals([“B”, “A”, “C”]) // true

Especially since the additional qualification over “equals” serves to emphasize 
the “lexographically” in reading the API (ie: not just “equals” but 
“lexographically equals”). Sure, maybe that’s a mis-reading of 
“lexicographically”, but it’s a pretty natural one, and a quick non-scientific 
poll of a few developers I work with had either a similar reading, or didn’t 
know what the function might mean. In either case, this naming seems contrary 
to the Swift API goal of “Clarity at the call site”.

So -1 from me for this name.

If we really want to rename this, what about something like:

[“A”, “B”, “C”].isOrderedEqual(to: [“B”, “A”, “C”]) // false
[“A”, “B”, “C”].isOrderedEqual(to: [“A”, “B”, “C”]) // true
[“A”, “B”, “C”].isOrderedEqual(to: [“A”, “B”, “D”]) // false

---

On the other hand, I’m also very much +1 for “Split Iterable out of Sequence” 
as soon as possible (even 4.x if possible)

Yes, this will be a breaking change. But the longer we let this obviously wrong 
modeling of Dictionary & Set linger, 1) the bigger a breaking change it will 
be, and 2) the more fundamentally unsafe code and undefined behavior will be 
written in Swift, directly undermining the language’s claims to safety by 
design. 

Perhaps we could mitigate some of the breakage by retaining the “broken” 
interfaces on Iterable with deprecation notices, but I haven’t through that 
through very much.

—Karim

> On Oct 13, 2017, at 5:52 PM, swift-evolution-requ...@swift.org wrote:
> 
> From: Christopher Whidden  >
> To: Xiaodi Wu >
> Cc: swift-evolution  >
> Subject: Re: [swift-evolution] [Draft] Rename Sequence.elementsEqual
> Message-ID:  >
> Content-Type: text/plain; charset="utf-8"
> 
> Using the term “lexicographically” implies to me that the Element type must 
> conform to Comparable, as would be required for a total order.  The Sequence 
> method you mention, lexicographicallyPrecedes(_:), does have this constraint, 
> whereas the method in question for elementsEqual(_:) / 
> lexicographicallyEquals(_:) only has the constraint that the Element is 
> Equatable.  As an example, an array of simple enums has no default 
> lexicographical ordering but is still able to use this method because enums 
> (without associated values) are Equatable by default:
> 
> enum Foo {
>case bar
>case baz
> }
> 
> let f1 = [Foo.bar, Foo.baz]
> let f2 = [Foo.baz, Foo.bar]
> 
> f1.elementsEqual(f2) //false
> f1.elementsEqual(f2.reversed()) //true
> 
> I also share Jonathan’s concerns that some programmers may misinterpret 
> [lexicographically][Equals] to mean [sorted in lexicographical order][compare 
> sequence equality], which is not what the method in question does.
> 
> Xiaodi, I think you are right that Sequence.sequentiallyEquals is to close to 
> "==" to use, but I think we have to find something better here.
> 
> I’ll recommend that we use the name Sequence.iterativelyEquals(_:) since this 
> describes the body of the method concisely.  A rough abbreviation of this 
> algorithm is:
> 
> 1. Iterate over elements in two sequences
>   a. Compare elements for equality
> 
> “iterativelyEquals" concisely describes this.
> 
>> On Oct 12, 2017, at 6: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.
>> 
>> > >Motivation
>> 
>> As outlined by Ole Begemann 
>> > 

Re: [swift-evolution] (core library) modern URL types

2017-08-22 Thread Karim Nassar via swift-evolution
IMHO, The fact that URL has distinct interfaces for ‘scheme', ‘user', ‘host', 
‘port', ‘query', and ‘fragment’ (all of which are either irrelevant or invalid 
for addressing local files) should be an indication that it’s maybe not the 
best primary interface for directly modeling filesystem interactions.

To my mind, the fact that a ‘file’ scheme exists for URLs speaks more to the 
fact that "*when* you are operating on URLs, it’s *sometimes* useful to be able 
to talk about local files", as opposed to "*when* you talk about files, you 
should *always* use URLs".

OTOH, I really like the idea of a first-class file path abstraction. Seems like 
there are a lot of nice opportunities for pattern & traversal abstractions, 
uniformity, etc.

—Karim


> Date: Tue, 22 Aug 2017 09:24:57 -0700
> From: Dave DeLong 
> To: Félix Cloutier 
> Cc: Chris Lattner via swift-evolution 
> Subject: Re: [swift-evolution] (core library) modern URL types
> Message-ID: <5124d1ae-cb31-4298-9d52-12318bb7a...@apple.com>
> Content-Type: text/plain; charset="utf-8"
> 
> I completely agree. URL packs a lot of punch, but IMO it’s the wrong 
> abstraction for file system paths.
> 
> I maintain an app that deals a lot with file system paths, and using URL has 
> always felt cumbersome, but String is the absolute wrong type to use. Lately 
> as I’ve been working on it, I’ve been experimenting with a concrete “Path” 
> type, similar to PathKit (https://github.com/kylef/PathKit/ 
> ). Working in terms of AbsolutePath and 
> RelativePath (what I’ve been calling things) has been extremely refreshing, 
> because it allows me to better articulate the kind of data I’m dealing with. 
> URL doesn’t handle pure-relative paths very well, and it’s always a bit of a 
> mystery how resilient I need to be about checking .isFileURL or whatever. All 
> the extra properties (port, user, password, host) feel hugely unnecessary as 
> well.
> 
> Dave
> 
>> On Aug 20, 2017, at 11:23 PM, Félix Cloutier via swift-evolution 
>>  wrote:
>> 
>> I'm not convinced that URLs are the appropriate abstraction for a file 
>> system path. For the record, I'm not a fan of existing Foundation methods 
>> that create objects from an URL. There is a useful and fundamental 
>> difference between a local path and a remote path, and conflating the two 
>> has been a security pain point in many languages and frameworks that allow 
>> it. Examples include remote file inclusion in PHP and malicious doctypes in 
>> XML. Windows also had its share of issues with UNC paths.
>> 
>> Even when loading an arbitrary URL looks innocuous, many de-anonymizing 
>> hacks work by causing a program to access an URL controlled by an attacker 
>> to make it disclose the user's IP address or some other identifier.
>> 
>> IMO, this justifies that there should be separate types to handle local and 
>> remote resources, so that at least developers have to be explicit about 
>> allowing remote resources. This makes a new URL type less necessary towards 
>> supporting file I/O.
>> 
>> Félix
>> 
>>> Le 20 août 2017 à 21:37, Taylor Swift via swift-evolution 
>>> > a écrit :
>>> 
>>> Okay so a few days ago there was a discussion 
>>> 
>>>  about getting pure swift file system support into Foundation or another 
>>> core library, and in my opinion, doing this requires a total overhaul of 
>>> the `URL` type (which is currently little more than a wrapper for NSURL), 
>>> so I’ve just started a pure Swift URL library project at 
>>> >.
>>> 
>>> The library’s parsing and validation core (~1K loc pure swift) is already 
>>> in place and functional; the goal is to eventually support all of the 
>>> Foundation URL functionality.
>>> 
>>> The new `URL` type is implemented as a value type with utf8 storage backed 
>>> by an array buffer. The URLs are just 56 bytes long each, so they should be 
>>> able to fit into cache lines. (NSURL by comparison is over 128 bytes in 
>>> size; it’s only saved by the fact that the thing is passed as a reference 
>>> type.)
>>> 
>>> As I said, this is still really early on and not a mature library at all 
>>> but everyone is invited to observe, provide feedback, or contribute!
>>> ___
>>> 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

Re: [swift-evolution] [Concurrency] async/await + actors

2017-08-21 Thread Karim Nassar via swift-evolution
Thought about it in more depth, and I’m now firmly in the camp of: 
‘throws’/‘try' and ‘async’/‘await' should be orthogonal features. I think the 
slight call-site reduction in typed characters ('try await’ vs ‘await’) is 
heavily outweighed by the loss of clarity on all the edge cases.

—Karim

> On Aug 21, 2017, at 1:56 PM, John McCall <rjmcc...@apple.com> wrote:
> 
>> 
>> On Aug 20, 2017, at 3:56 PM, Yuta Koshizawa <ko...@koherent.org 
>> <mailto:ko...@koherent.org>> wrote:
>> 
>> 2017-08-21 2:20 GMT+09:00 John McCall via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>>:
>>> On Aug 19, 2017, at 7:17 PM, Chris Lattner via swift-evolution 
>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>>> On Aug 19, 2017, at 8:14 AM, Karim Nassar via swift-evolution 
>>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>>> 
>>>> This looks fantastic. Can’t wait (heh) for async/await to land, and the 
>>>> Actors pattern looks really compelling.
>>>> 
>>>> One thought that occurred to me reading through the section of the 
>>>> "async/await" proposal on whether async implies throws:
>>>> 
>>>> If ‘async' implies ‘throws' and therefore ‘await' implies ‘try’, if we 
>>>> want to suppress the catch block with ?/!, does that mean we do it on the 
>>>> ‘await’ ? 
>>>> 
>>>> guard let foo = await? getAFoo() else {  …  }
>>> 
>>> Interesting question, I’d lean towards “no, we don’t want await? and 
>>> await!”.  My sense is that the try? and try! forms are only occasionally 
>>> used, and await? implies heavily that the optional behavior has something 
>>> to do with the async, not with the try.  I think it would be ok to have to 
>>> write “try? await foo()” in the case that you’d want the thrown error to 
>>> turn into an optional.  That would be nice and explicit.
>> 
>> try? and try! are quite common from what I've seen.
>> 
>> As analogous to `throws` and `try`, I think we have an option that `await!` 
>> means blocking.
>> 
>> First, if we introduce something like `do/catch` for `async/await`, I think 
>> it should be for blocking. For example:
>> 
>> ```
>> do {
>>   return await foo()
>> } block
>> ```
>> 
>> It is consistent with `do/try/catch` because it should allow to return a 
>> value from inside `do` blocks for an analogy of `throws/try`.
>> 
>> ```
>> // `throws/try`
>> func foo() -> Int {
>>   do {
>> return try bar()
>>   } catch {
>> ...
>>   }
>> }
>> 
>> // `async/await`
>> func foo() -> Int {
>>   do {
>> return await bar()
>>   } block
>> }
>> ```
>> 
>> And `try!` is similar to `do/try/catch`.
>> 
>> ```
>> // `try!`
>> let x = try! foo()
>> // uses `x` here
>> 
>> // `do/try/catch`
>> do {
>>   let x = try foo()
>>   // uses `x` here
>> } catch {
>>   fatalError()
>> }
>> ```
>> 
>> If `try!` is a sugar of `do/try/catch`, it also seems natural that `await!` 
>> is a sugar of `do/await/block`. However, currently all `!` in Swift are 
>> related to a logic failure. So I think using `!` for blocking is not so 
>> natural in point of view of symbology.
>> 
>> Anyway, I think it is valuable to think about what `do` blocks for 
>> `async/await` mean. It is also interesting that thinking about combinations 
>> of `catch` and `block` for `async throws` functions: e.g. If only `block`, 
>> the enclosing function should be `throws`.
> 
> Personally, I think these sources of confusion are a good reason to keep the 
> feature separate.
> 
> The idea of using await! to block a thread is interesting but, as you say, 
> does not fit with the general meaning of ! for logic errors.  I think it's 
> fine to just have an API to block waiting for an async operation, and we can 
> choose the name carefully to call out the danger of deadlocks.
> 
> John.
> 
>> 
>> That aside, I think `try!` is not so occasional and is so important. Static 
>> typing has limitations. For example, even if we has a text field which 
>> allows to input only numbers, we still get an input value as a string and 
>> parsing it may fail on its type though it actually never fails. If we did 
>> not have easy ways to convert such a simple domain error or a recoverable 
>> error to a logic failure, people would start ignoring them as we has seen in 
>> Java by `catch(Exception e) {}`. Now we have `JSONDecoder` and we will see 
>> much more `try!` for bundled JSON files in apps or generated JSONs by code, 
>> for which decoding fails as a logic failure.
>> 
>> --
>> Yuta

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


Re: [swift-evolution] [Concurrency] async/await + actors

2017-08-19 Thread Karim Nassar via swift-evolution

> On Aug 19, 2017, at 7:17 PM, Chris Lattner <clatt...@nondot.org> wrote:
> 
> 
>> On Aug 19, 2017, at 8:14 AM, Karim Nassar via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>> This looks fantastic. Can’t wait (heh) for async/await to land, and the 
>> Actors pattern looks really compelling.
>> 
>> One thought that occurred to me reading through the section of the 
>> "async/await" proposal on whether async implies throws:
>> 
>> If ‘async' implies ‘throws' and therefore ‘await' implies ‘try’, if we want 
>> to suppress the catch block with ?/!, does that mean we do it on the ‘await’ 
>> ? 
>> 
>> guard let foo = await? getAFoo() else {  …  }
> 
> Interesting question, I’d lean towards “no, we don’t want await? and await!”. 
>  My sense is that the try? and try! forms are only occasionally used, and 
> await? implies heavily that the optional behavior has something to do with 
> the async, not with the try.  I think it would be ok to have to write “try? 
> await foo()” in the case that you’d want the thrown error to turn into an 
> optional.  That would be nice and explicit.
> 
> -Chris
> 


I’d be curious to see numbers on the prevalence of try?/! across various kinds 
of codebases (i.e.: library code, app code, CLI utils, etc). I don’t use try? 
all that much, but I have used it. I also have found (IMHO) legitimate uses for 
try! in my unit tests where I want the test logic to be brittle with respect to 
expected conditions surrounding the test—to fail immediately if those 
conditions are not as I intend them to be.

If we can write "try? await foo()” (which I think is the right way to position 
this), will we be able to also write "try await foo()” ?  I’d hope that the 
latter wouldn’t be prohibited… as I think it would just make the former less 
discoverable. If I’m learning Swift and I see “try? await” on one line, and 
nearby just “await” it’s easier to assume that the first can produce an error 
and the second can’t, no?

If I’m honest, I *think* I’d rather we'd always have to be explicit about both 
try and await… yes it’s more to type, but it’s also a lot clearer about what 
exactly is happening. And if I always use "do try catch” together it forms a 
consistent pattern that’s easier to read and easier to learn. If sometimes it’s 
“do try catch” and sometimes "do await catch” and sometimes just “await" it 
seems to me we’ve lost some clarity and it’s harder for me to compose my 
understanding of the rules.

On the other hand, I can’t say I’ve given this a lot of deep thought either :)

—Karim

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


Re: [swift-evolution] [Concurrency] async/await + actors

2017-08-19 Thread Karim Nassar via swift-evolution
This looks fantastic. Can’t wait (heh) for async/await to land, and the Actors 
pattern looks really compelling.

One thought that occurred to me reading through the section of the 
"async/await" proposal on whether async implies throws:

If ‘async' implies ‘throws' and therefore ‘await' implies ‘try’, if we want to 
suppress the catch block with ?/!, does that mean we do it on the ‘await’ ? 

guard let foo = await? getAFoo() else {  …  }

This looks a little odd to me, not not extremely clear as to what is happening. 
Under what conditions will we get a nil instead of a Foo? Maybe it’s just me or 
that the syntax is new and I’ll get used to it.

But it gets even more complicated if we have:

func getAFoo() async -> Foo {
   …
}

func getABar() async(nonthrowing) -> Bar {
   …
}

Now, we have an odd situation where the ‘await’ keyword may sometimes accept 
?/! but in other cases may not (or it has no meaning):

guard 
   let foo = await? getAFoo(),
   let bar = await? getABar() // Is this an error?? If not, what does it mean?
   else {  …  }


Since this edge of throws/try wasn’t explicitly covered in the write-up (or did 
I miss it?), was wondering about your thoughts.

—Karim


> Date: Thu, 17 Aug 2017 15:24:14 -0700
> From: Chris Lattner 
> To: swift-evolution 
> Subject: [swift-evolution] [Concurrency] async/await + actors
> 
> Hi all,
> 
> As Ted mentioned in his email, it is great to finally kick off discussions 
> for what concurrency should look like in Swift.  This will surely be an epic 
> multi-year journey, but it is more important to find the right design than to 
> get there fast.
> 
> I’ve been advocating for a specific model involving async/await and actors 
> for many years now.  Handwaving only goes so far, so some folks asked me to 
> write them down to make the discussion more helpful and concrete.  While I 
> hope these ideas help push the discussion on concurrency forward, this isn’t 
> in any way meant to cut off other directions: in fact I hope it helps give 
> proponents of other designs a model to follow: a discussion giving extensive 
> rationale, combined with the long term story arc to show that the features 
> fit together.
> 
> Anyway, here is the document, I hope it is useful, and I’d love to hear 
> comments and suggestions for improvement:
> https://gist.github.com/lattner/31ed37682ef1576b16bca1432ea9f782
> 
> -Chris



___
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-08 Thread Karim Nassar via swift-evolution
> On Apr 6, 2017, at 1:35 PM, Joe Groff via swift-evolution 
> > wrote:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md
>  
>   
> >
>   • What is your evaluation of the proposal?

-1 because I don’t think this proposal is fully baked. We definitely need this 
feature, but we need more discussion on the details.

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

Yes. There are many practical and pragmatic reasons to want to embed multi-line 
string literals in code, and most of these use-cases are hampered or made more 
significantly more fiddly with continuation characters or concatenation, for 
all the reasons already discussed.

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

This is where things break down. This proposal feels like we took Python’s 
approach and slapped it on Swift. There are more ways to do this than identical 
open-close delimiters with magic whitespace stripping. 

Non-exhasutive ideas for other options we should weigh (all spellings are 
straw-men):

1. Open/close delimiters: 
let msg = @“ // optionally: @4” to strip 4 chars leading whitespace
this is a
message
"@

2. A “Swifty” Heredoc compiler directive:
let msg = #stringUntil(END) // optionally: #stringUntil(END, stripLeading: 
4)
this is a
message
END

3. Other options as mentioned on this list

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

This is pretty much the Python approach with some additional vague 
whitespace-stripping rules. We need to think it through better and then 
re-introduce after proper discussion.

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

Read the proposal, followed the discussion.

> 
> 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-03 Thread Karim Nassar via swift-evolution

> For me, -1 for two reasons:
> 
> - Mainly, it still encourages stuffing everything into one file. I don't 
> claim that having a 50-line files is the goal, but neither is having 1500 
> lines of code within one file. With less complex types, you're mostly fine 
> with private/fileprivate as they are. For more complex types, you want to 
> split the type across a few files making it better readable and organized. 
> This doesn't help.

Absolutely -1 for me too (emphasis added). More churn on what ‘private’ means 
isn’t going to make anyone happy.

I’d much rather do nothing right now, and solve this problem for real later 
when we can actually solve this major pain-point for organizing Swift code. 
Having the file as the only intermediate organizational code unit between the 
module- and a type-boundaries is incredibly painful currently. 

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


Re: [swift-evolution] Smart KeyPaths

2017-03-31 Thread Karim Nassar via swift-evolution

> Date: Fri, 31 Mar 2017 04:33:43 -0700
> From: Brent Royal-Gordon 
> To: Haravikk 
> Cc: Haravikk via swift-evolution 
> Subject: Re: [swift-evolution] Smart KeyPaths
> Message-ID: 
> Content-Type: text/plain; charset="utf-8"
> 
>> On Mar 31, 2017, at 3:07 AM, Haravikk via swift-evolution 
>>  wrote:
>> 
>> Is it actually in-use or just reserved? Not sure I've ever needed it in the 
>> debugger.
> 
> Pop into the REPL for a minute:
> 
>   $ swift
>   Welcome to Apple Swift version 3.1 (swiftlang-802.0.41 clang-802.0.36). 
> Type :help for assistance.
> 1> "hello"
>   $R0: String = "hello"
> 2> $R0
>   $R1: String = "hello"
> 
> You may not have ever noticed it was there, but it was.
> 
>> What about @? It has a certain appropriateness in how it reads for a path 
>> like: @Person.friend.lastName
> 
> We're already using @ for attributes; I don't think we want to overload its 
> meaning.
> 
>> Another alternative might be something like an unnamed compiler directive, 
>> for example: #(Person.friend.lastName)
>> If you consider the statement to mean "expand this".
> 
> The unnamed compiler directive seems like *really* valuable real estate, 
> arguably much more so than unresolved-member-on-KeyPath-type is. I think it'd 
> be foolish to assign it to anything before we have a macro system designed.


I agree that #() is too valuable to burn at this point. 

So… Crazy Thought: Is KeyPath enough of a term-of-art beyond ObjC that we want 
to carry it’s semantics directly into Swift even when it conflicts with 
established ObjC inter-op? In other words, if we didn’t already know ObjC & 
KVO/KVC, does “KeyPath” mean what we mean by it in Swift?

If the issue is the conflict with the current semantics of #keyPath(), what 
about something like:

```
   let fooProp: Property = #property(bar.bast)
```

And in the inferred/ambiguous case:

```
let fooProp = #property(bar.bast, of: Foo)
```

It perhaps moves too far from the KeyPath nomenclature, but it reads rather 
nicely (IMHO).

—Karim




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


Re: [swift-evolution] [Pitch] String revision proposal #1

2017-03-30 Thread Karim Nassar via swift-evolution

> Message: 12
> Date: Thu, 30 Mar 2017 12:23:13 +0200
> From: Adrian Zubarev 
> To: Ben Cohen 
> Cc: swift-evolution@swift.org
> Subject: Re: [swift-evolution] [Pitch] String revision proposal #1
> Message-ID: 
> Content-Type: text/plain; charset="utf-8"
> 
> I haven’t followed the topic and while reading the proposal I found it a 
> little confusing that we have inconsistent type names. I’m not a native 
> English speaker so that’s might be the main case for my confusion here, so 
> I’d appreciate for any clarification. ;-)
> 
> SubSequence vs. Substring and not SubString.
> 
> The word substring is an English word, but so is subsequence (I double 
> checked here).
> 
> So where exactly is the issue here? Is it SubSequence which is written in 
> camel case or is it Substring which is not?
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail


I’d also be curious if StringSlice was considered, since we have already the 
well-established and seemingly-parallel ArraySlice.

—Karim

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0159: Fix Private Access Levels

2017-03-24 Thread Karim Nassar via swift-evolution
> What is your evaluation of the proposal?
A very reluctant -1. “Reluctant" because I suspect that we won’t get another 
chance to revisit this, and I *do* think it’s broken.

I’m in the camp that believes the result we got out of SE-25 was not helpful to 
the evolution of Swift, and I would like to see us reverse the decision. I 
strongly believe that -25 was a mistake, and took access controls in the wrong 
direction. 

However, I’m not blind to the fact that while *I* don’t have much use for 
`private` in its Swift3 meaning, there are others who are making good use of 
it. I have no desire to make the language less expressive for them. 

I *would* be strongly supportive of a proposal to rename `private` -> `scoped` 
and `fileprivate` -> `private`. This would solve many of the confusion & 
complications resulting from -25 without making the language less expressive 
for those currently depending on `private`. Alas, that is not the proposal 
being evaluated.

> Is the problem being addressed significant enough to warrant a change to 
> Swift?
While I believe that there is a significant problem that needs to be addressed 
with regards to access controls in Swift, I don’t believe this proposal 
sufficiently addresses it.

Adding more expressiveness at the smallest end of the visibility spectrum 
(SE-25) has simply aggravated the “Very Large File” syndrome that continues to 
plague my Swift projects. IMHO, what we really need is more expressiveness in 
the *middle* of the spectrum (i.e.: between the Module `internal` and the file 
`file/private` expression so that we can hide details of tightly coupled 
implementations within a larger module without glomming all those 
implementations into a single file.

This proposal doesn’t actually solve the problem, it simply pretties-up the 
spelling of `fileprivate` and removes a feature (scoped private) that some 
members of the community seem to depend on. 

> Does this proposal fit well with the feel and direction of Swift?
Yes. I believe that the spelling `fileprivate` is clunky and inelegant and 
creates cognitive dissonance by coexisting with `private`, and that private has 
a non-intuitive meaning to anyone not being taught Swift as their first PL.

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

> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?
Have followed the discussion since SE-25 was passed. Have been using Swift 
since its announcement, studied the proposal and considered its implications 
for some time.

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


Re: [swift-evolution] Smart KeyPaths

2017-03-23 Thread Karim Nassar via swift-evolution

> I guess I just don't understand why people seem so eager to change this 
> syntax. The biggest complaint seems to be that it's too lightweight and 
> natural; they're worried they might not realize they're using this big, scary 
> new feature. But this feature simply *isn't* big and scary! It's new right 
> now, but in a few years it's going to feel very natural.
> 
> […]
> 
> Key paths are about as nonthreatening as a syntax can be. They overload some 
> things, but the type checker will catch most overloading mistakes. Other than 
> that, there's just no justification for the level of anxiety people seem to 
> have. They don't break type safety, they don't involve unusual or non-obvious 
> control flow, they don't trap, and they can be explained in a couple of 
> sentences. If ever there was a candidate for a lightweight syntax, this is 
> it. 
> 
> As the protest sign says: "I want YOU to stop being afraid". I have yet to be 
> convinced that this feature is too dangerous or mistake-prone to allow the 
> simple, natural syntax the authors propose. If I'm wrong, then by all means 
> show me I'm wrong, but I just don't see it.


I don’t have a strong opinion on the sigil question one way or another, but I’m 
not sure it’s fair to categorize the sigil proponents as being afraid of the 
feature. I do find the argument that some kind of sigil to clarify the 
construction-site of a KeyPath somewhat compelling.

KeyPath declarations as described in the proposal are fairly unique in that 
they have all the appearance of accessing a property value on a type, but are 
in fact a mechanism for “creating” (referencing?) a type entirely different 
from their face-value. That is: a KeyPath shares most of its spelling with the 
value that it points to, and absent knowledge of the programmer’s *intent* it’s 
not immediately obvious whether code is accessing a value or creating a 
KeyPath. They are references to a named member of a type which are derived by 
their name.

IMHO, it’s not *that* unreasonable to want a spelling variation to call 
attention to this difference.

In any case, as I said, I’m not strongly opinionated on this matter, but 
perhaps it *is* worth considering some sigil we could apply to both KeyPath and 
function assignments to clarify both sites in the same way.

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


Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-06 Thread Karim Nassar via swift-evolution

> On Mar 6, 2017, at 3:04 AM, Rien  wrote:
> 
 
 I’m not dead-set on this approach, but as you say, it solves a *lot* of 
 problems that other approaches introduce. I do recognize the 
 reasonableness of the main argument against, that file location shouldn’t 
 have such a dramatic affect on behavior… *but* the fact is (whether by 
 convention or expediency) we already *do* have filesystem location 
 dependencies on our code projects… 
 
 * One can’t willy-nilly move files around the disk and expect a project to 
 build… if you move it somewhere the compiler doesn’t know to look for it, 
 you’re going to break things
 * One can’t just move a file out of your SCM repo root, or you’ll “lose” 
 the file
>>> 
>>> True, but if other files do not refer to the lost file, you don’t even know 
>>> for which file to look.
>>> (imo this is already a weak point in swift, but this approach to submodules 
>>> would make it -much?- worse)
>>> 
>>> If you were to include filenames in the “submodule declaration file” at 
>>> least this omission in swift would be partly covered, and you would not 
>>> need to move the other files into special places. (You could though)
>>> 
>> 
>> But isn’t this exactly the same case if you’re using Swift without an IDE? 
>> It’s true that Xcode keeps track of files in your project, and there’s no 
>> reason it couldn’t also keep track of files in a submodule (in fact it 
>> would… it just might not know they belong in the sub-module without some 
>> work from the Xcode dev team).
>> 
>> But as a thought-experiment, here’s how I’m thinking of this problem:
>> 
>> Swift (as a language) has established that a file *is* a unit of code. Not 
>> the only one of course, but it is one, as evidenced by access controls 
>> (fileprivate, Swift2 private) which bound on the file.
> 
> I disagree with this: Swift is just a set of -more or less- arbitrary rules 
> to allow the development of applications.
> The criteria for those rules are chosen by the core team and will fluctuate 
> with time.
> As such there is no “Swift way” of doing things. Any such remark is by its 
> nature a personal preference. (not that there is anything wrong with that, 
> its just not an argument)
> 
> (Besides, a computer only knows files, thus of course a file is a unit of 
> code. That does not mean we should extend “code” to be something outside the 
> files)

First, that’s simply not true. In Swift 1, a file was *not* a logical unit of 
code because file boundaries were meaningless to the way the code in the 
project behaved. In Swift 2 we got `private` which made it possible for file 
boundaries to affect code behavior. Swift 3 changed `private` but introduced 
`fileprivate` for the same purpose.

Second, yes, Swift is just a language, but as that language evolves, it is an 
expression of the values & preferences of its development team and more 
recently, this community. If the file was not *intended* to be a unit of code, 
we would not have `fileprivate`.


>> I (and many others) want to be able to describe another unit of code larger 
>> than a file and smaller than a Module to help organize the file-units we 
>> have which go together within a Module, but which shouldn’t (for various 
>> reasons) describe a complete Module in and of themselves.
> 
> Sure, and I have nothing against that. However I an dead set against 
> extending the scope of the language itself to the organisation of its files. 
> It is traditional to leave the organisation of the files to the configuration 
> of the compiler/linker. And I do not see how it would simplify the language 
> itself by extending the language to cover file organisation.

Clearly adding any new feature will not simplify the language. The questions 
are 1) should we add this feature, and 2) how to add the feature. I *do* take 
your objections to heart and that’s why I added some alternatives not involving 
the filesystem to my proposal. These alternatives each have their own problems 
and complications which we can discuss… maybe they’re not as bad as they seem, 
maybe they’re worse, and *probably*—because I’m just one person—there are 
solutions to the problem which I haven’t thought of.

> I will predict that if this approach is taken you should brace for the storm 
> that would want to reverse this feature. It would imo dwarf the private vs 
> fileprivate debate.

And no one wants that. That’s why we are having this discussion, no? I’ll be 
honest, I saw the fileprivate/private discussion on this list, and didn’t voice 
my opinion then because I thought “oh, they’ll do the right thing”, then was 
unhappy with what we got. That’s the reason I’ve started this discussion, and 
it’s also the reason I *really* value your dissenting input. I want not just 
*a* solution, but *the right* solution, and I know I don’t know everything that 
needs knowing to come up with it alone.

I and many others want a 

Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-05 Thread Karim Nassar via swift-evolution


> On Mar 5, 2017, at 2:06 PM, Xiaodi Wu <xiaodi...@gmail.com> wrote:
> 
> Punycode would readily cover your first issue about legal identifier 
> characters.

Well, it would cover… I’m not sure if “readily” would be the right word.

If I have a sub-module I want to call `Bücher`, and I have to name the 
directory `Bcher-kva`, what do I use to refer to the sub-module in my code? 
It’s not at all readable, nor is it discoverable to a 3rd party who if they 
don’t “know” about Punycode, have no reason to associate the `Bücher` 
sub-module with the `Bcher-kva` directory.

Not that’s a show-stopper, mind. I wouldn’t mind further exploring the 
directory-name + “extension" approach.

—Karim

> As to the second, having enumerated the essential properties of a Foo, what 
> "growth" are you envisioning?
> On Sun, Mar 5, 2017 at 12:51 Karim Nassar via swift-evolution 
> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
> 
>> On Mar 5, 2017, at 10:10 AM, Rien <r...@balancingrock.nl 
>> <mailto:r...@balancingrock.nl>> wrote:
>> 
>>> 
>>> On 05 Mar 2017, at 15:52, Karim Nassar via swift-evolution 
>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> 
>>>> On Mar 4, 2017, at 2:54 PM, Matthew Johnson <matt...@anandabits.com 
>>>> <mailto:matt...@anandabits.com>> wrote:
>>>> 
>>>>> 
>>>>> On Mar 4, 2017, at 9:56 AM, Karim Nassar <ka...@karimnassar.com 
>>>>> <mailto:ka...@karimnassar.com>> wrote:
>>>>> 
>>>>> 
>>>>>> On Mar 3, 2017, at 5:21 PM, Matthew Johnson <matt...@anandabits.com 
>>>>>> <mailto:matt...@anandabits.com>> wrote:
>>>>>> 
>>>>>>> 
>>>>>>> On Mar 3, 2017, at 9:24 AM, Karim Nassar via swift-evolution 
>>>>>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>>>>>> 
>>>>>>> Changes that *are* necessary are:
>>>>>>> 
>>>>>>> * Change the spelling of `internal` to `module` (making `module` the 
>>>>>>> new default)
>>>>>>> * Introduce a new modifier `internal` to mean "Internal to the current 
>>>>>>> sub-module and its child-sub-modules”
>>>>>> 
>>>>>> Can you give concrete examples of use cases where a descendent submodule 
>>>>>> needs access to symbols declared by an ancestor?  I gave some thought to 
>>>>>> this when drafting my proposal and came to the conclusion that this runs 
>>>>>> against the grain of layering and is likely to be a bad idea in 
>>>>>> practice.  If there are use cases I didn’t consider I am very interested 
>>>>>> in learning about them.
>>>>> 
>>>>> On further reflection and examination of my notes, I think you’re right, 
>>>>> and that the `internal` encapsulation should be purely horizontal. Will 
>>>>> adjust to reflect that.
>>>>> 
>>>>>>> ### Making a Sub-module
>>>>>>> 
>>>>>>> To create a sub-module within a Module (or sub-module) is simple: The 
>>>>>>> author creates a directory, and places a "sub-module declaration file" 
>>>>>>> within the directory:
>>>>>>> 
>>>>>>> ```
>>>>>>> //  __submodule.swift
>>>>>> 
>>>>>> Why the double underscore prefix?  To make it sort to the top in a file 
>>>>>> browser?
>>>>>> 
>>>>>> Is this file allowed to have any Swift code?  Or is it limited to 
>>>>>> submodule-related declarations only?  If the latter, why not use an 
>>>>>> extension such as `.submodule` or `.swiftmodule` to differentiate it 
>>>>>> from ordinary Swift files and allow the submodule to be named by the 
>>>>>> name of this file?
>>>>> 
>>>>> So, my reasoning was that by requiring a specific standard name for the 
>>>>> declaration file, we guarantee that any directory can only describe one 
>>>>> submodule. Prefixing the proposed name with underscores was simply a way 
>>>>> of preventing naming collision with potential “real code” files (and yes, 
>>>>> as a side-effect alpha-floating it to the top). Since the

Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-05 Thread Karim Nassar via swift-evolution

> On Mar 5, 2017, at 10:10 AM, Rien <r...@balancingrock.nl> wrote:
> 
>> 
>> On 05 Mar 2017, at 15:52, Karim Nassar via swift-evolution 
>> <swift-evolution@swift.org> wrote:
>> 
>> 
>>> On Mar 4, 2017, at 2:54 PM, Matthew Johnson <matt...@anandabits.com> wrote:
>>> 
>>>> 
>>>> On Mar 4, 2017, at 9:56 AM, Karim Nassar <ka...@karimnassar.com> wrote:
>>>> 
>>>> 
>>>>> On Mar 3, 2017, at 5:21 PM, Matthew Johnson <matt...@anandabits.com> 
>>>>> wrote:
>>>>> 
>>>>>> 
>>>>>> On Mar 3, 2017, at 9:24 AM, Karim Nassar via swift-evolution 
>>>>>> <swift-evolution@swift.org> wrote:
>>>>>> 
>>>>>> Changes that *are* necessary are:
>>>>>> 
>>>>>> * Change the spelling of `internal` to `module` (making `module` the new 
>>>>>> default)
>>>>>> * Introduce a new modifier `internal` to mean "Internal to the current 
>>>>>> sub-module and its child-sub-modules”
>>>>> 
>>>>> Can you give concrete examples of use cases where a descendent submodule 
>>>>> needs access to symbols declared by an ancestor?  I gave some thought to 
>>>>> this when drafting my proposal and came to the conclusion that this runs 
>>>>> against the grain of layering and is likely to be a bad idea in practice. 
>>>>>  If there are use cases I didn’t consider I am very interested in 
>>>>> learning about them.
>>>> 
>>>> On further reflection and examination of my notes, I think you’re right, 
>>>> and that the `internal` encapsulation should be purely horizontal. Will 
>>>> adjust to reflect that.
>>>> 
>>>>>> ### Making a Sub-module
>>>>>> 
>>>>>> To create a sub-module within a Module (or sub-module) is simple: The 
>>>>>> author creates a directory, and places a "sub-module declaration file" 
>>>>>> within the directory:
>>>>>> 
>>>>>> ```
>>>>>> //  __submodule.swift
>>>>> 
>>>>> Why the double underscore prefix?  To make it sort to the top in a file 
>>>>> browser?
>>>>> 
>>>>> Is this file allowed to have any Swift code?  Or is it limited to 
>>>>> submodule-related declarations only?  If the latter, why not use an 
>>>>> extension such as `.submodule` or `.swiftmodule` to differentiate it from 
>>>>> ordinary Swift files and allow the submodule to be named by the name of 
>>>>> this file?
>>>> 
>>>> So, my reasoning was that by requiring a specific standard name for the 
>>>> declaration file, we guarantee that any directory can only describe one 
>>>> submodule. Prefixing the proposed name with underscores was simply a way 
>>>> of preventing naming collision with potential “real code” files (and yes, 
>>>> as a side-effect alpha-floating it to the top). Since the `submodule` 
>>>> declaration might expand to include statements & configuration about the 
>>>> sub-module, I see no reason to prohibit Swift code from existing in that 
>>>> sub-module declaration file… Disallowing/controlling that seems to be a 
>>>> style/linter concern.
>>>> 
>>>> However, as I mentioned above, all the specific spellings (except 
>>>> `internal`)  for the different concepts in this proposal are straw-men 
>>>> awaiting input. I’d say the addition of a new type of file extension 
>>>> raises some concerns for me, but there’s already been a lot of push back 
>>>> on the general idea of using filesystem structures to organize 
>>>> sub-modules, so the whole idea may be moot. 
>>> 
>>> I’ve actually been starting to come around to the idea of using the file 
>>> system.  Not so much because I really like it, but because I have been 
>>> considering further some of the drawbacks of other approaches.  
>>> 
>>> One big reason is that a submodule should form a scope and scopes should 
>>> consist of code that is physically adjacent.  In practice this means it 
>>> should reside in close proximity in the file system.  Allowing any file in 
>>> a project to be a part of any submodule partly defeats the purpose of using 
>>> them to structure a project internally.  If w

Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-05 Thread Karim Nassar via swift-evolution

> On Mar 4, 2017, at 2:54 PM, Matthew Johnson <matt...@anandabits.com> wrote:
> 
>> 
>> On Mar 4, 2017, at 9:56 AM, Karim Nassar <ka...@karimnassar.com 
>> <mailto:ka...@karimnassar.com>> wrote:
>> 
>> 
>>> On Mar 3, 2017, at 5:21 PM, Matthew Johnson <matt...@anandabits.com 
>>> <mailto:matt...@anandabits.com>> wrote:
>>> 
>>>> 
>>>> On Mar 3, 2017, at 9:24 AM, Karim Nassar via swift-evolution 
>>>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>>>> 
>>>> Changes that *are* necessary are:
>>>> 
>>>> * Change the spelling of `internal` to `module` (making `module` the new 
>>>> default)
>>>> * Introduce a new modifier `internal` to mean "Internal to the current 
>>>> sub-module and its child-sub-modules”
>>> 
>>> Can you give concrete examples of use cases where a descendent submodule 
>>> needs access to symbols declared by an ancestor?  I gave some thought to 
>>> this when drafting my proposal and came to the conclusion that this runs 
>>> against the grain of layering and is likely to be a bad idea in practice.  
>>> If there are use cases I didn’t consider I am very interested in learning 
>>> about them.
>> 
>> On further reflection and examination of my notes, I think you’re right, and 
>> that the `internal` encapsulation should be purely horizontal. Will adjust 
>> to reflect that.
>> 
>>>> ### Making a Sub-module
>>>> 
>>>> To create a sub-module within a Module (or sub-module) is simple: The 
>>>> author creates a directory, and places a "sub-module declaration file" 
>>>> within the directory:
>>>> 
>>>> ```
>>>> //  __submodule.swift
>>> 
>>> Why the double underscore prefix?  To make it sort to the top in a file 
>>> browser?
>>> 
>>> Is this file allowed to have any Swift code?  Or is it limited to 
>>> submodule-related declarations only?  If the latter, why not use an 
>>> extension such as `.submodule` or `.swiftmodule` to differentiate it from 
>>> ordinary Swift files and allow the submodule to be named by the name of 
>>> this file?
>> 
>> So, my reasoning was that by requiring a specific standard name for the 
>> declaration file, we guarantee that any directory can only describe one 
>> submodule. Prefixing the proposed name with underscores was simply a way of 
>> preventing naming collision with potential “real code” files (and yes, as a 
>> side-effect alpha-floating it to the top). Since the `submodule` declaration 
>> might expand to include statements & configuration about the sub-module, I 
>> see no reason to prohibit Swift code from existing in that sub-module 
>> declaration file… Disallowing/controlling that seems to be a style/linter 
>> concern.
>> 
>> However, as I mentioned above, all the specific spellings (except 
>> `internal`)  for the different concepts in this proposal are straw-men 
>> awaiting input. I’d say the addition of a new type of file extension raises 
>> some concerns for me, but there’s already been a lot of push back on the 
>> general idea of using filesystem structures to organize sub-modules, so the 
>> whole idea may be moot. 
> 
> I’ve actually been starting to come around to the idea of using the file 
> system.  Not so much because I really like it, but because I have been 
> considering further some of the drawbacks of other approaches.  
> 
> One big reason is that a submodule should form a scope and scopes should 
> consist of code that is physically adjacent.  In practice this means it 
> should reside in close proximity in the file system.  Allowing any file in a 
> project to be a part of any submodule partly defeats the purpose of using 
> them to structure a project internally.  If we’re going to be organizing the 
> files in a submodule physically anyway maybe we should just take advantage of 
> that fact and prevent a stray file in a distant part of the file system from 
> being part of the submodule.
> 
> The second reason is that there is a big problem with placing a simple 
> `submodule Foo` declaration at the top of each file in a submodule.  We all 
> make typos from time to time.  This method makes it too easy to accidentally 
> type `submodule Fooo` and end up in a submodule you didn’t intend.  This 
> mistake would likely be caught relatively quickly but it seems silly to have 
> a system subject to this kind of mistake.  This means we

Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-04 Thread Karim Nassar via swift-evolution
Here is a new gist with updates based on all the great feedback I’ve received 
(accidentally created the first one anonymously):

https://gist.github.com/knassar/5c9933207663dad7eeb29ff7c526af62

And inline:

# Sub-modules

A sub-module solution in Swift should have the following properties:

* Extremely light-weight
* Low API surface area
* Adopt progressive disclosure
* Integrate with Access Control features to enable a level of encapsulation & 
hiding between the Module and File level
* Be permeable when desired

## Discussion

As we get deeper into building real applications & frameworks with Swift, we 
begin to realize that having a way to express relationships between types is 
desireable.  Currently, Swift only allows us to express these relationships at 
two levels, the Module and the File. 

The Module boundary is acceptable for small, focused frameworks, while the File 
boundary is acceptable for small, focused Types, but both levels can be 
unweildy when dealing with certain cases where a cluster of internally related 
types needs to know about each other but may only want to publish a narrow set 
of APIs to the surrounding code, or in large complex applications which are 
necessarily structured as a single Module. In these cases, we wind up with 
large monolithic Modules or (even worse) large monolithic Files.

I have seen this proliferation of Huge Sprawling Files (HSFs) in my own code, 
and seek a way to combat this rising tide.

## Goals 

It is a goal of this proposal to:

* Suggest a mechanism for organizing code between the Module and File levels 
that is as lightweight and low-friction as possible
* Provide mechanisms for authors to create both "hard" and "soft" API 
boundaries between the Module and File levels of their code

## Anti-Goals

It is not a goal of this proposal to:

* Move Swift away from filesystem-based organization
* Significantly alter the current Access Control philosophy of Swift

## Proposal Notes

Please take the following proposal wholely as a Straw-Man... I would be equally 
satisfied with any solution which meets the critera described at the top of 
this document.

Unless specified otherwise, all spellings proposed below are to be considered 
straw-men, and merely illustrative of the concepts.

# Proposed Solution

Two things are clear to me after using Swift and following the Swift Evolution 
list since their respective publications:

1. Swift has a preference for file-based organization
2. Vocal Swift Users dislike `fileprivate` and want to revert to Swift2-style 
`private`

Because of #1, this proposal does not seek to change Swift's inherent 
file-system organization, and instead will expand on it.

Since I personally fall into the camp described by #2, and most of the 
community response to this has been "Lets wait to deal with that until 
sub-modules", I'm making this proposal assuming that solving that quagmire is 
in-scope for this propsoal.

## Changes to Access Control Modifiers

As part of this proposal (or as a pre-requisite assumption), I suggest the 
following changes to Swift 3's Access Control modifiers:

* Revert `private` to Swift 2's meaning: "hidden outside the file"
* Remove `fileprivate` as redundant

This is potentially a source-breaking change. However, it is interesting to 
note that this change is **not** required for the following proposal to 
function.

Changes that *are* necessary are:

* Change the spelling of `internal` to `module` (making `module` the new 
default)
* Introduce a new modifier `internal` to mean "Internal to the current 
sub-module (or if at the 'top' level of a module, Internal to the top-level, 
ie: hidden from it's sub-modules)"

These changes are *not* source-breaking because the new `internal` modifier 
acts exactly as the old `internal` modifier when used without sub-modules. The 
specific spelling of this new `internal` modifier is necessary to maintain 
backwards source compatibility.

The new `module` modifier allows authors to make APIs permeable between 
sub-modules while still hidden outside the owning Module if desired.

All other Access Control modifiers behave the same as they currently do 
irrespective of sub-module boundaries, so:

* `public` => Visible outside the Module
* `open` => Sub-classable outside the Module

## Making a Sub-module

There are various alternative mechanisms that might be chosen for declaring a 
sub-module. I describe 3 of them here, each with some observations, pros, and 
cons. The intent of this proposal is to select **one** mechanism that best 
balances the proposal goals and the mechanism's compromises. Other alternatives 
are welome.

### Alternative 1: Using the Filesystem

To create a sub-module within a Module (or sub-module) is simple: The author 
creates a directory, and places a "sub-module declaration file" within the 
directory:

```
//  __submodule.swift
//  MyModule

submodule SubA

```

Then any files within that directory are part of the sub-module:

```
//  

Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-04 Thread Karim Nassar via swift-evolution

> On Mar 3, 2017, at 5:21 PM, Matthew Johnson <matt...@anandabits.com> wrote:
> 
>> 
>> On Mar 3, 2017, at 9:24 AM, Karim Nassar via swift-evolution 
>> <swift-evolution@swift.org> wrote:
>> 
>> Changes that *are* necessary are:
>> 
>> * Change the spelling of `internal` to `module` (making `module` the new 
>> default)
>> * Introduce a new modifier `internal` to mean "Internal to the current 
>> sub-module and its child-sub-modules”
> 
> Can you give concrete examples of use cases where a descendent submodule 
> needs access to symbols declared by an ancestor?  I gave some thought to this 
> when drafting my proposal and came to the conclusion that this runs against 
> the grain of layering and is likely to be a bad idea in practice.  If there 
> are use cases I didn’t consider I am very interested in learning about them.

On further reflection and examination of my notes, I think you’re right, and 
that the `internal` encapsulation should be purely horizontal. Will adjust to 
reflect that.

>> ### Making a Sub-module
>> 
>> To create a sub-module within a Module (or sub-module) is simple: The author 
>> creates a directory, and places a "sub-module declaration file" within the 
>> directory:
>> 
>> ```
>> //  __submodule.swift
> 
> Why the double underscore prefix?  To make it sort to the top in a file 
> browser?
> 
> Is this file allowed to have any Swift code?  Or is it limited to 
> submodule-related declarations only?  If the latter, why not use an extension 
> such as `.submodule` or `.swiftmodule` to differentiate it from ordinary 
> Swift files and allow the submodule to be named by the name of this file?

So, my reasoning was that by requiring a specific standard name for the 
declaration file, we guarantee that any directory can only describe one 
submodule. Prefixing the proposed name with underscores was simply a way of 
preventing naming collision with potential “real code” files (and yes, as a 
side-effect alpha-floating it to the top). Since the `submodule` declaration 
might expand to include statements & configuration about the sub-module, I see 
no reason to prohibit Swift code from existing in that sub-module declaration 
file… Disallowing/controlling that seems to be a style/linter concern.

However, as I mentioned above, all the specific spellings (except `internal`)  
for the different concepts in this proposal are straw-men awaiting input. I’d 
say the addition of a new type of file extension raises some concerns for me, 
but there’s already been a lot of push back on the general idea of using 
filesystem structures to organize sub-modules, so the whole idea may be moot. 

Shortly, I’m going to update the original proposal gist reflecting all the 
comments I’ve received and part of that will be expanding the proposal section 
to include multiple alternate strategies for discussion, along with pros/cons 
for each. I’ll include a discussion on naming options for this file in this 
section.

> If we’re going to use the file system to organize submodules this seems like 
> a reasonable approach.  It allows larger submodules to have folder 
> hierarchies within them and also creates a central location for 
> submodule-related declarations.
> 
> A primary flaw I see in this approach is that Xcode is the dominant IDE for 
> Swift and the way Xcode handles files is not conducive to file-system 
> organization.  I really detest the way Xcode handles this and would vastly 
> prefer that it simply reflected the physical file system hierarchy but I 
> don’t think that will change any time soon.  On the other hand maybe a file 
> system based submodule system in Swift would motivate the Xcode team to 
> better reflect the physical file system organization.


My thoughts (hopes?) on this were that should Swift adopt such a mechanism for 
sub-modules, then part of Xcode’s integration of the feature would be to make 
it aware of sub-modules in a first-class way, so that the author wouldn’t have 
to manually manage the project files to take advantage of the feature. 

I’d envisioned either a new “Makes Sub-Module” property on Groups or a new 
“Sub-Module" mechanism alongside Groups & Folders in the project list. This may 
be wishful thinking on my part.

—Karim




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


Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-03 Thread Karim Nassar via swift-evolution

> On Mar 3, 2017, at 1:13 PM, Karim Nassar  wrote:
> 
>> 
>> On Mar 3, 2017, at 12:35 PM, David Hart > > wrote:
>> 
>>> 
>>> ### Making a Sub-module
>>> 
>>> To create a sub-module within a Module (or sub-module) is simple: The 
>>> author creates a directory, and places a "sub-module declaration file" 
>>> within the directory:
>>> 
>>> ```
>>> //  __submodule.swift
>>> //  MyModule
>>> 
>>> submodule SubA
>>> 
>>> ```
>> 
>> Like the previous response, I think this potentially the weakest part of he 
>> proposal. I like the idea of a file-system based submodule system but I'm 
>> not sure I like this version of it. People are going to be very vocal about 
>> this too. Perhaps you could rewrite the proposal with several solutions for 
>> this part? Let people discuss the different solutions.
> 
> Thanks, this is exactly why I posted this original concept—to spur 
> conversation.
> 
> An alternate approach might be to eliminate the “magic file” and directory 
> dependency and replace them with explicit sub-module adoption per file. 
> Something like this:
> 
> **all spellings are straw-men!**
> 
> ```
> // declared in any file
> 
> // this is the same sub-module declaration previously declared in the magic 
> file, 
> // and serves the same purpose of declaring the sub-module, 
> // and acting as a home for future configuration:
> 
> submodule SubA 
> 
> 
> // announced once in any file you wish to include in the sub-module:
> 
> in_submodule SubA
> 
> ```
> 
> Some issues I see with this:
> increases the surface area— need to introduce a new declaration for 
> announcing sub-module inclusion
> Either: 
> introduces a new *kind* of declaration… `in_submodule` which can only appear 
> once in a file (which would need to be compiler-enforced), OR:
> increases complexity by allowing multiple sub-module declarations in a file
> 

Yet another possible approach is to treat the sub-module as a 
symbolically-named scope (in plain-English, I’d call it a meta-type, but that 
already means something). This is similar mechanically to one of the earlier 
proposals:

```
submodule SubA { }

extension SubA {
struct Foo {  }

submodule SubB { 
struct Bar {  }
}
}

extension SubA.SubB {
struct Bast {  }
}

```

Pros:

* Extends an existing pattern in a somewhat reasonable-seeming way, easily 
discoverable

Cons:

* Though the pattern *seems* reasonable, it’s actually an odd-duck; a 
sub-module does not behave the same as a type in many important ways.
* There’s some impact here on how top-level declarations are evaluated (i.e.: 
Protocols, global statements, etc). 
* Visually uglier (indentation)
* The mental model required for this is **much** more complicated, as submodule 
declarations can now be mixed within a file, and the (file)private Access 
Controls will span sub-modules.

—Karim



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


Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-03 Thread Karim Nassar via swift-evolution

> On Mar 3, 2017, at 12:35 PM, David Hart <da...@hartbit.com> wrote:
> 
> I strongly agree with all your points. The other submodule proposals are too 
> complex for me so I'm very happy to see a different solution which more 
> closely fits my design priorities.
> 

Thanks David,

> Comments inline:
> 
>> On 3 Mar 2017, at 16:24, Karim Nassar via swift-evolution 
>> <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
>> 
>> 
>> I’ve read through the last couple of Swift (sub)Module proposals put 
>> forward, and since my particular use-cases for a sub-module solution seemed 
>> to be under-served by them, I’ve decided to write up my thoughts on the 
>> matter to prompt discussion. 
>> 
>> Perhaps my use-cases are outliers, and my approach will be deemed naive by 
>> the community… I’m happy to learn better ways of doing things in Swift, and 
>> welcome any thoughts, criticism, or illumination related to these ideas.
> 
> I don't think your use cases are outliers. I think your solution really feels 
> more Swifty by starting simple.
> 
>> I’m including the write-up below, but it’s also available as a gist: 
>> https://gist.github.com/anonymous/9806f4274f1e13860670d6e059be5dce 
>> <https://gist.github.com/anonymous/9806f4274f1e13860670d6e059be5dce>
>> 
>> —
>> 
>> # Sub-modules
>> 
>> A sub-module solution in Swift should have the following properties:
>> 
>> * Extremely light-weight
>> * Low API surface area
>> * Adopt progressive disclosure
>> * Integrate with Access Control features to enable a level of encapsulation 
>> & hiding between the Module and File level
>> * Be permeable when desired
> 
> Yes, yes, yes. Very good goals :)

:)

>> ## Discussion
>> 
>> As we get deeper into building real applications & frameworks with Swift, we 
>> begin to realize that having a way to express relationships between types is 
>> desireable. Currently, Swift only allows us to express these relationships 
>> at two levels, the Module and the File. 
>> 
>> The Module boundary is acceptable for small, focused frameworks, while the 
>> File boundary is acceptable for small, focused Types, but both levels can be 
>> unweildy when dealing with certain cases where a cluster of internally 
>> related types needs to know about each other but may only want to publish a 
>> narrow set of APIs to the surrounding code, or in large complex applications 
>> which are necessarily structured as a single Module. In these cases, we wind 
>> up with large monolithic Modules or (even worse) large monolithic Files.
>> 
>> I have seen this proliferation of Huge Sprawling Files (HSFs) in my own 
>> code, and seek a way to combat this rising tide.
>> 
>> ## Goals 
>> 
>> It is a goal of this proposal to:
>> 
>> * Suggest a mechanism for organizing code between the Module and File levels 
>> that is as lightweight and low-friction as possible
>> * Provide mechanisms for authors to create both "hard" and "soft" API 
>> boundaries between the Module and File levels of their code
>> 
>> ## Anti-Goals
>> 
>> It is not a goal of this proposal to:
>> 
>> * Move Swift away from filesystem-based organization
>> * Significantly alter the current Access Control philosophy of Swift
>> 
>> ## Proposal Notes
>> 
>> Please take the following proposal wholely as a Straw-Man... I would be 
>> equally satisfied with any solution which meets the critera described at the 
>> top of this document.
>> 
>> Unless specified otherwise, all spellings proposed below are to be 
>> considered straw-men, and merely illustrative of the concepts.
>> 
>> ## Proposed Solution
>> 
>> Two things are clear to me after using Swift and following the Swift 
>> Evolution list since their respective publications:
>> 
>> 1. Swift has a preference for file-based organization
>> 2. Vocal Swift Users dislike `fileprivate` and want to revert to 
>> Swift2-style `private`
>> 
>> Because of #1, this proposal does not seek to change Swift's inherent 
>> file-system organization, and instead will expand on it.
>> 
>> Since I personally fall into the camp described by #2, and most of the 
>> community response to this has been "Lets wait to deal with that until 
>> sub-modules", I'm making this proposal assuming that solving that quagmire 
>> is in-scope for this propsoal.
> 
> I have posted a proposal which proposes #2. It should hopefully get 

Re: [swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-03 Thread Karim Nassar via swift-evolution
Thanks for your feedback. 

These are very fair concerns and point taken. There are other mechanisms we 
could use to achieve similar ends, I’ll work on some additional ideas.

How do you view the overall goals/use cases?

—Karim

> On Mar 3, 2017, at 10:58 AM, Rien <r...@balancingrock.nl> wrote:
> 
> I don’t like the file location based approach taken, see inline.
> 
> Rien.
> 
>> On 03 Mar 2017, at 16:24, Karim Nassar via swift-evolution 
>> <swift-evolution@swift.org> wrote:
>> 
>> 
>> I’ve read through the last couple of Swift (sub)Module proposals put 
>> forward, and since my particular use-cases for a sub-module solution seemed 
>> to be under-served by them, I’ve decided to write up my thoughts on the 
>> matter to prompt discussion. 
>> 
>> Perhaps my use-cases are outliers, and my approach will be deemed naive by 
>> the community… I’m happy to learn better ways of doing things in Swift, and 
>> welcome any thoughts, criticism, or illumination related to these ideas.
>> 
>> I’m including the write-up below, but it’s also available as a gist: 
>> https://gist.github.com/anonymous/9806f4274f1e13860670d6e059be5dce
>> 
>> —
>> 
>> # Sub-modules
>> 
>> A sub-module solution in Swift should have the following properties:
>> 
>> * Extremely light-weight
>> * Low API surface area
>> * Adopt progressive disclosure
>> * Integrate with Access Control features to enable a level of encapsulation 
>> & hiding between the Module and File level
>> * Be permeable when desired
>> 
>> ## Discussion
>> 
>> As we get deeper into building real applications & frameworks with Swift, we 
>> begin to realize that having a way to express relationships between types is 
>> desireable. Currently, Swift only allows us to express these relationships 
>> at two levels, the Module and the File. 
>> 
>> The Module boundary is acceptable for small, focused frameworks, while the 
>> File boundary is acceptable for small, focused Types, but both levels can be 
>> unweildy when dealing with certain cases where a cluster of internally 
>> related types needs to know about each other but may only want to publish a 
>> narrow set of APIs to the surrounding code, or in large complex applications 
>> which are necessarily structured as a single Module. In these cases, we wind 
>> up with large monolithic Modules or (even worse) large monolithic Files.
>> 
>> I have seen this proliferation of Huge Sprawling Files (HSFs) in my own 
>> code, and seek a way to combat this rising tide.
>> 
>> ## Goals 
>> 
>> It is a goal of this proposal to:
>> 
>> * Suggest a mechanism for organizing code between the Module and File levels 
>> that is as lightweight and low-friction as possible
>> * Provide mechanisms for authors to create both "hard" and "soft" API 
>> boundaries between the Module and File levels of their code
>> 
>> ## Anti-Goals
>> 
>> It is not a goal of this proposal to:
>> 
>> * Move Swift away from filesystem-based organization
>> * Significantly alter the current Access Control philosophy of Swift
>> 
>> ## Proposal Notes
>> 
>> Please take the following proposal wholely as a Straw-Man... I would be 
>> equally satisfied with any solution which meets the critera described at the 
>> top of this document.
>> 
>> Unless specified otherwise, all spellings proposed below are to be 
>> considered straw-men, and merely illustrative of the concepts.
>> 
>> ## Proposed Solution
>> 
>> Two things are clear to me after using Swift and following the Swift 
>> Evolution list since their respective publications:
>> 
>> 1. Swift has a preference for file-based organization
>> 2. Vocal Swift Users dislike `fileprivate` and want to revert to 
>> Swift2-style `private`
>> 
>> Because of #1, this proposal does not seek to change Swift's inherent 
>> file-system organization, and instead will expand on it.
>> 
>> Since I personally fall into the camp described by #2, and most of the 
>> community response to this has been "Lets wait to deal with that until 
>> sub-modules", I'm making this proposal assuming that solving that quagmire 
>> is in-scope for this propsoal.
>> 
>> ### Changes to Access Control Modifiers
>> 
>> As part of this proposal, I suggest the following changes to Swift 3's 
>> Access Control modifiers:
>> 
>> * Revert `private` to Swift 2's meaning: "hidden outside the file"
>> * Remove `fi

[swift-evolution] Yet Another Take on Swift Sub-modules

2017-03-03 Thread Karim Nassar via swift-evolution

I’ve read through the last couple of Swift (sub)Module proposals put forward, 
and since my particular use-cases for a sub-module solution seemed to be 
under-served by them, I’ve decided to write up my thoughts on the matter to 
prompt discussion. 

Perhaps my use-cases are outliers, and my approach will be deemed naive by the 
community… I’m happy to learn better ways of doing things in Swift, and welcome 
any thoughts, criticism, or illumination related to these ideas.

I’m including the write-up below, but it’s also available as a gist: 
https://gist.github.com/anonymous/9806f4274f1e13860670d6e059be5dce

—

# Sub-modules

A sub-module solution in Swift should have the following properties:

* Extremely light-weight
* Low API surface area
* Adopt progressive disclosure
* Integrate with Access Control features to enable a level of encapsulation & 
hiding between the Module and File level
* Be permeable when desired

## Discussion

As we get deeper into building real applications & frameworks with Swift, we 
begin to realize that having a way to express relationships between types is 
desireable.  Currently, Swift only allows us to express these relationships at 
two levels, the Module and the File. 

The Module boundary is acceptable for small, focused frameworks, while the File 
boundary is acceptable for small, focused Types, but both levels can be 
unweildy when dealing with certain cases where a cluster of internally related 
types needs to know about each other but may only want to publish a narrow set 
of APIs to the surrounding code, or in large complex applications which are 
necessarily structured as a single Module. In these cases, we wind up with 
large monolithic Modules or (even worse) large monolithic Files.

I have seen this proliferation of Huge Sprawling Files (HSFs) in my own code, 
and seek a way to combat this rising tide.

## Goals 

It is a goal of this proposal to:

* Suggest a mechanism for organizing code between the Module and File levels 
that is as lightweight and low-friction as possible
* Provide mechanisms for authors to create both "hard" and "soft" API 
boundaries between the Module and File levels of their code

## Anti-Goals

It is not a goal of this proposal to:

* Move Swift away from filesystem-based organization
* Significantly alter the current Access Control philosophy of Swift

## Proposal Notes

Please take the following proposal wholely as a Straw-Man... I would be equally 
satisfied with any solution which meets the critera described at the top of 
this document.

Unless specified otherwise, all spellings proposed below are to be considered 
straw-men, and merely illustrative of the concepts.

## Proposed Solution

Two things are clear to me after using Swift and following the Swift Evolution 
list since their respective publications:

1. Swift has a preference for file-based organization
2. Vocal Swift Users dislike `fileprivate` and want to revert to Swift2-style 
`private`

Because of #1, this proposal does not seek to change Swift's inherent 
file-system organization, and instead will expand on it.

Since I personally fall into the camp described by #2, and most of the 
community response to this has been "Lets wait to deal with that until 
sub-modules", I'm making this proposal assuming that solving that quagmire is 
in-scope for this propsoal.

### Changes to Access Control Modifiers

As part of this proposal, I suggest the following changes to Swift 3's Access 
Control modifiers:

* Revert `private` to Swift 2's meaning: "hidden outside the file"
* Remove `fileprivate` as redundant

This is potentially a source-breaking change. However, it is interesting to 
note that this change is **not** required for the following proposal to 
function.

Changes that *are* necessary are:

* Change the spelling of `internal` to `module` (making `module` the new 
default)
* Introduce a new modifier `internal` to mean "Internal to the current 
sub-module and its child-sub-modules"

These changes are *not* source-breaking because the new `internal` modifier 
acts exactly as the old `internal` modifier unless it is used within a 
sub-module. The specific spelling of this new `internal` modifier is necessary 
to maintain backwards source compatibility.

The new `module` modifier allows authors to make APIs permeable between 
sub-modules while still hidden outside the owning Module if desired.

All other Access Control modifiers behave the same as they currently do 
irrespective of sub-module boundaries, so:

* `public` => Visible outside the Module
* `open` => Sub-classable outside the Module

### Making a Sub-module

To create a sub-module within a Module (or sub-module) is simple: The author 
creates a directory, and places a "sub-module declaration file" within the 
directory:

```
//  __submodule.swift
//  MyModule

submodule SubA

```

Then any files within that directory are part of the sub-module:

```
//  Foo.swift
//  MyModule.SubA

struct Foo {
private var 

Re: [swift-evolution] Consolidate Code for Each Case in Enum

2017-01-09 Thread Karim Nassar via swift-evolution

Although I appreciate the intent, I too find the proposed sugar far more noisy 
and harder to read than the more typical approach.

But:

TLDR; Simplifying the accessing of enum associated values would be worthy of 
some syntactic sugar in my opinion.

One area of enums that I’d love to see some sugar wrapped around (and perhaps 
this has already been discussed previously?) is extracting associated values.

There are many times where, given an enum like:

enum Feedback {
case ok
case info(String)
case warning(String, Location)
case error(String, Location)
}

I’d love it if we could tag the associated values with some semantic accessor, 
perhaps borrowed from tuples:

enum Feedback {
case ok
case info(msg: String)
case warning(msg: String, loc: Location)
case error(msg: String, loc: Location)
}

then:

let foo = self.getSomeFeedback() // -> Feedback
if let msg = foo.msg { // since not all cases can hold a ‘msg’ .msg is an 
Optional
print(foo)
}

I know this is a trivial example, since there are only 4 cases, but I have 
enums with many more cases where many of the cases share some common semantic 
themes, and producing large switch statements to exercise all of the possible 
patterns that might hold a given associated value can be verbose to the point 
of illegibility.

I know there is also the (IMHO terrible) "if let case” incantation, but I can 
never remember how it is spelled, and its even harder to read, IMHO.

—Karim


> I don't think I've ever wanted to distribute the patterns of a switch 
> statement across multiple files.  It seems like you want an enum of enums if 
> the code you're writing needs this kind of chunking.  Distributing cases is 
> also far more brittle than the existing local switch; failing to include a 
> file in the build that covers necessary cases now becomes a module-level 
> error rather than a statement-local one. Finally, the proposal seems to do 
> the opposite of consolidate and simplify code by introducing quite a lot of 
> syntax around what it aims to do, and by muddying the meaning of a keyword 
> that was previously only meant for types.
> 
> A few conceptual questions:
> 
> How does this interact with versioned cases?  
> What about enums that carry values?
> 
> ~Robert Widmann
> 
> 2017/01/06 23:59、Tim Shadel via swift-evolution  > のメッセージ:
> 
>> Idea: Consolidate the Code for Each Case in an Enum
>> 
>> # Motivation:
>> 
>> Consolidate all code related to a single enum case in one spot. This makes 
>> it easier to ensure that all the pieces mesh coherently across that one case.
>> 
>> # Background:
>> 
>> Enum cases _feel_ like separately defined, but tightly related structs 
>> because each case can have distinct associated values. They have special 
>> privileges that a family of structs doesn't have, like `self = .otherCase`. 
>> Enums are really awesome.
>> 
>> # Proposed Solution:
>> 
>> Any `func` or dynamic `var` that provides a unique response per `case` uses 
>> a `switch` to do so. I propose to hide that standard `switch` behind some 
>> syntactic sugar. Possibly `extension MyEnum.myCase`, assuming that nothing 
>> extra is allowed there (protocol conformance, generic constraints, etc.).
>> 
>> Here's a typical example of a (simplified) enum that represents 2 states, 
>> and conforms to 2 protocols, each requiring different dynamic values based 
>> on the case of the enum. In both places, an outer `switch` is used to select 
>> the current enum case, and the logic within each branch further determines 
>> the value returned.
>> 
>> ```
>> protocol State {
>>mutating func react(to event: Event)
>> }
>> 
>> enum TokenState: State, CustomStringConvertible {
>> 
>>case expired(at: Date)
>>case validated(token: String)
>> 
>>var description: String {
>>  switch self {
>>case let .expired(at):
>>return "Expired at \(at)"
>>case let .validated(token):
>>return "Token \(token) has been validated."
>>  }
>>}
>> 
>>mutating func react(to event: Event) {
>>switch self {
>>case .expired:
>>switch event {
>>case _ as TokenRefreshed:
>>self = .validated(token: event.token)
>>default:
>>break
>>}
>>case .validated:
>>switch event {
>>case _ as TokenRejected:
>>self = .expired(at: Date())
>>case _ as UserLoggedOut:
>>self = .expired(at: Date())
>>default:
>>break
>>}
>>}
>>}
>> 
>> }
>> ```
>> 
>> If we instead allow all the code for each enum case to be consolidated, this 
>> new code looks much more like the rest of the code we write in Swift. Real 
>> world enums frequently have many more cases, and as the number of enum cases 
>> grows 

Re: [swift-evolution] Consolidate Code for Each Case in Enum

2017-01-08 Thread Karim Nassar via swift-evolution

Although I appreciate the intent, I too find the proposed sugar far more noisy 
and harder to read than the more typical approach.

But:

TLDR; Simplifying the accessing of enum associated values would be worthy of 
some syntactic sugar in my opinion.

One area of enums that I’d love to see some sugar wrapped around (and perhaps 
this has already been discussed previously?) is extracting associated values.

There are many times where, given an enum like:

enum Feedback {
case ok
case info(String)
case warning(String, Location)
case error(String, Location)
}

I’d love it if we could tag the associated values with some semantic accessor, 
perhaps borrowed from tuples:

enum Feedback {
case ok
case info(msg: String)
case warning(msg: String, loc: Location)
case error(msg: String, loc: Location)
}

then:

let foo = self.getSomeFeedback() // -> Feedback
if let msg = foo.msg { // since not all cases can hold a ‘msg’ .msg is an 
Optional
print(foo)
}

I know this is a trivial example, since there are only 4 cases, but I have 
enums with many more cases where many of the cases share some common semantic 
themes, and producing large switch statements to exercise all of the possible 
patterns that might hold a given associated value can be verbose to the point 
of illegibility.

I know there is also the (IMHO terrible) "if let case” incantation, but I can 
never remember how it is spelled, and its even harder to read, IMHO.

—Karim


> I don't think I've ever wanted to distribute the patterns of a switch 
> statement across multiple files.  It seems like you want an enum of enums if 
> the code you're writing needs this kind of chunking.  Distributing cases is 
> also far more brittle than the existing local switch; failing to include a 
> file in the build that covers necessary cases now becomes a module-level 
> error rather than a statement-local one. Finally, the proposal seems to do 
> the opposite of consolidate and simplify code by introducing quite a lot of 
> syntax around what it aims to do, and by muddying the meaning of a keyword 
> that was previously only meant for types.
> 
> A few conceptual questions:
> 
> How does this interact with versioned cases?  
> What about enums that carry values?
> 
> ~Robert Widmann
> 
> 2017/01/06 23:59、Tim Shadel via swift-evolution  > のメッセージ:
> 
>> Idea: Consolidate the Code for Each Case in an Enum
>> 
>> # Motivation:
>> 
>> Consolidate all code related to a single enum case in one spot. This makes 
>> it easier to ensure that all the pieces mesh coherently across that one case.
>> 
>> # Background:
>> 
>> Enum cases _feel_ like separately defined, but tightly related structs 
>> because each case can have distinct associated values. They have special 
>> privileges that a family of structs doesn't have, like `self = .otherCase`. 
>> Enums are really awesome.
>> 
>> # Proposed Solution:
>> 
>> Any `func` or dynamic `var` that provides a unique response per `case` uses 
>> a `switch` to do so. I propose to hide that standard `switch` behind some 
>> syntactic sugar. Possibly `extension MyEnum.myCase`, assuming that nothing 
>> extra is allowed there (protocol conformance, generic constraints, etc.).
>> 
>> Here's a typical example of a (simplified) enum that represents 2 states, 
>> and conforms to 2 protocols, each requiring different dynamic values based 
>> on the case of the enum. In both places, an outer `switch` is used to select 
>> the current enum case, and the logic within each branch further determines 
>> the value returned.
>> 
>> ```
>> protocol State {
>>mutating func react(to event: Event)
>> }
>> 
>> enum TokenState: State, CustomStringConvertible {
>> 
>>case expired(at: Date)
>>case validated(token: String)
>> 
>>var description: String {
>>  switch self {
>>case let .expired(at):
>>return "Expired at \(at)"
>>case let .validated(token):
>>return "Token \(token) has been validated."
>>  }
>>}
>> 
>>mutating func react(to event: Event) {
>>switch self {
>>case .expired:
>>switch event {
>>case _ as TokenRefreshed:
>>self = .validated(token: event.token)
>>default:
>>break
>>}
>>case .validated:
>>switch event {
>>case _ as TokenRejected:
>>self = .expired(at: Date())
>>case _ as UserLoggedOut:
>>self = .expired(at: Date())
>>default:
>>break
>>}
>>}
>>}
>> 
>> }
>> ```
>> 
>> If we instead allow all the code for each enum case to be consolidated, this 
>> new code looks much more like the rest of the code we write in Swift. Real 
>> world enums frequently have many more cases, and as the number of enum cases 
>> grows