Re: [swift-evolution] final + lazy + fileprivate modifiers

2017-02-19 Thread Goffredo Marocchi via swift-evolution
Maybe the burden of proof required for this change is not met even though it 
frustrates those who dislike fileprivate. I honestly think our energies are 
better spent on other parts of the language than arguing on this... unless the 
discussion has time to grow into a proper holistic manifesto on access controls 
and goes beyond the current "let's just kill fileprivate and make private 
behave like it".

The current private provides useful functionality for a way of composing and 
designing objects... fileprivate is four more characters and most of us use 
autocompletion features on modern IDE's now, does what it says on the tin, 
provides no issue to newcomers really, and it is not clear to me we have a 
better alternative... we all adopted this current approach for a reason, the 
core team did not trip into it.


Also, do we have data about this being an issue? For an opinionated language 
and opinionated audience, this is a bit OT and we should discuss it in a 
different thread, we should be gathering data and help it drive our opinions 
(to back claims about better stability, higher performance, etc...).

Sent from my iPhone

> On 19 Feb 2017, at 23:52, Tony Arnold via swift-evolution 
>  wrote:
> 
> 
>> On 20 Feb 2017, at 06:25, Jose Cheyo Jimenez via swift-evolution 
>>  wrote:
>> 
>> We need more examples to make this case. 
> 
> How do we provide those examples? This thread has been actively discussed for 
> close to a week now, so it would be good to do something concrete about it. I 
> think Chris’ second suggestion fits my idea of a reasonable “Default” level 
> of privacy when starting out, and fits the model of progressive disclosure as 
> you so excellently pointed out.
> 
> Is this something that should go through a proper Proposal? Is someone doing 
> this already? I’d like to help/contribute if it is.
> 
> thanks,
> 
> 
> Tony
> 
> 
> 
> --
> Tony Arnold
> +61 411 268 532
> http://thecocoabots.com/
> 
> ABN: 14831833541
> 
> ___
> 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] final + lazy + fileprivate modifiers

2017-02-19 Thread Jose Cheyo Jimenez via swift-evolution


> On Feb 19, 2017, at 10:31 PM, David Hart  wrote:
> 
> 
> 
>> On 20 Feb 2017, at 00:52, Tony Arnold via swift-evolution 
>>  wrote:
>> 
>> 
>>> On 20 Feb 2017, at 06:25, Jose Cheyo Jimenez via swift-evolution 
>>>  wrote:
>>> 
>>> We need more examples to make this case. 
>> 
>> How do we provide those examples? This thread has been actively discussed 
>> for close to a week now, so it would be good to do something concrete about 
>> it. I think Chris’ second suggestion fits my idea of a reasonable “Default” 
>> level of privacy when starting out, and fits the model of progressive 
>> disclosure as you so excellently pointed out.
>> 
>> Is this something that should go through a proper Proposal? Is someone doing 
>> this already? I’d like to help/contribute if it is.
> 
> Chris' second suggestion was dropped by Chris himself after we discussed the 
> disadvantages it adds. I am already working on a proposal to revert to Swift 
> 2's private and it should be ready soon. 

I think this is a good strategy, the alternatives should include keeping scope 
private but with a different name. Focus on specific code examples and specify 
how having two overlapping specifiers is harmful.   This is how we were able to 
reverse only being able to use if let instead of if var 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160125/008145.html



>> thanks,
>> 
>> 
>> Tony
>> 
>> 
>> 
>> --
>> Tony Arnold
>> +61 411 268 532
>> http://thecocoabots.com/
>> 
>> ABN: 14831833541
>> 
>> ___
>> 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] Treating an Enum's Cases as Its Subtypes

2017-02-19 Thread Niels Andriesse via swift-evolution
I'd like to discuss the possibility of treating the cases of a given enum
as if they are subtypes of that enum. This seems like a natural thing to do
because enum cases (especially when they have associated values)
effectively define a closed set of subtypes.

Doing so would allow for constructions such as the following:

enum Foo {
  case a(name: String)
}

func isA(foo: Foo) -> Bool {
  // The old way:
  if case .a = foo { return true }
  return false
  // The new way:
  return foo is .a
}

func printNameIfFooIsA(foo: Foo) -> Bool {
  // The old way:
  if case let .a(name) = foo {
print(name)
  }
  // The new way (1):
  if let a = foo as? .a {
print(a.name)
  }
  // The new way (2):
  if let name = (foo as? .a)?.name {
print(name)
  }
}

Treating an enum's cases as its subtypes would make enums easier to work
with because handling them would be syntactically the same as handling
other types.

The pattern matching capabilities of enums wouldn't be affected by this
proposal.

Multiple other proposals have already attempted to simplify enum handling
(they have particularly focused on getting rid of "if case" and adding the
ability to treat enum case tests as expressions), but none of the solutions
presented in those proposals have worked out so far.

I believe that this could be the right solution to multiple enum-related
problems that have been brought up repeatedly.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Dictionary Enhancements

2017-02-19 Thread Brent Royal-Gordon via swift-evolution
> On Feb 16, 2017, at 4:26 PM, Ben Cohen via swift-evolution 
>  wrote:
> 
>   • init from/merge in a Sequence of Key/Value pairs (already raised as 
> SE-100: 
> https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md).

Yes, I think this is a great idea.

>   • make the Values view collection a MutableCollection (as in this PR: 
> https://github.com/apple/swift-evolution/pull/555).

Sounds good to me.

>   • Add a defaulting subscript get (e.g. counts[key, default: 0] += 1 or 
> grouped(key, default:[]].append(value)).

I'd really like this to be a broader mechanism—either somehow permitting 
assignment through `??`:

(counts[key] ?? 0) += 1

Or having some kind of `Dictionary` variant with a default value:

var counts = DefaultedDictionary(elements, default: 0)
counts[key] += 1

>   • Add a group by-like init to create a Dictionary from a 
> sequence of V and a closure (V)->K.

Honestly, this is such a good idea that I might want it to be an extension 
method in `Sequence` or `Collection`:

extension Sequence {
func grouped(by makeKey: (Element) throws -> 
Key) rethrows -> [Key: Element] {…}
}

We don't expose `map` and `filter` as `Array` initializers; why would 
`grouped(by:)` be one?

>   • Add Dictionary.filter to return a Dictionary.

Sure. If it took a `(Key, Value) -> Bool` predicate, that could even 
distinguish between the `Array`-returning version and the `Dictionary` one.

>   • Add Dictionary.mapValues to return a Dictionary (can be more 
> efficiently implemented than composition as the storage layout remains the 
> same).

Yes, this is something I want.  So do 114 Stack Overflow users: 


I'd actually prefer that this *not* take a `Key` parameter, because that's more 
likely to interfere with point-free styles of programming. Reasonable people 
can disagree on that, though.

>   • Add capacity property and reserveCapacity() method.

Eh, maybe.

>   • Have Dictionary.removeAtIndex return the Index of the next entry.

I'm not sure what the point of this is, and I'm not sure if you think this 
should also be done to equivalent APIs on e.g. `RangeReplaceableCollection`.

>   • (once we have conditional conformance) Make dictionaries with 
> Equatable values Equatable.

No-brainer—definitely want this one.

> Please reply here with any comments or questions on the above list, or any 
> additions you believe are important that are missing from it.

I'd sort of like to see a protocol for key-value lookup types, sort of like 
`SetAlgebra` but for dictionaries. I've recently been building a custom 
dictionary (a `SortedDictionary` type which sorts its elements by key) and not 
having a protocol to describe dictionaries abstractly is a bit of an irritant.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] final + lazy + fileprivate modifiers

2017-02-19 Thread David Hart via swift-evolution


> On 20 Feb 2017, at 00:52, Tony Arnold via swift-evolution 
>  wrote:
> 
> 
>> On 20 Feb 2017, at 06:25, Jose Cheyo Jimenez via swift-evolution 
>>  wrote:
>> 
>> We need more examples to make this case. 
> 
> How do we provide those examples? This thread has been actively discussed for 
> close to a week now, so it would be good to do something concrete about it. I 
> think Chris’ second suggestion fits my idea of a reasonable “Default” level 
> of privacy when starting out, and fits the model of progressive disclosure as 
> you so excellently pointed out.
> 
> Is this something that should go through a proper Proposal? Is someone doing 
> this already? I’d like to help/contribute if it is.

Chris' second suggestion was dropped by Chris himself after we discussed the 
disadvantages it adds. I am already working on a proposal to revert to Swift 
2's private and it should be ready soon. 

> thanks,
> 
> 
> Tony
> 
> 
> 
> --
> Tony Arnold
> +61 411 268 532
> http://thecocoabots.com/
> 
> ABN: 14831833541
> 
> ___
> 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] @selfsafe: a new way to avoid reference cycles

2017-02-19 Thread David Hart via swift-evolution

On 20 Feb 2017, at 06:05, Brent Royal-Gordon via swift-evolution 
 wrote:

>> On Feb 19, 2017, at 7:06 PM, Matthew Johnson  wrote:
>> 
>> Often you hand it to something owned by self, but it's also the case that 
>> you often hand it to something not owned by self, but that should not extend 
>> the lifetime of self.
> 
> I don't agree that it shouldn't extend the lifetime of `self`. By default, 
> Swift assumes that if you capture an object in a closure, you want that 
> object to stay alive as long as the closure does.
> 
> I see absolutely no reason that this assumption should be different for 
> `self` than it is for any other variable, and I see no reason to believe the 
> caller would have a particularly good idea about this.

Totally agree. The proposal would complicate reasoning about reference cycles 
and lifetime of objects by creating special cases which depend on what variable 
is concerned (self or other) and what the API does.

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

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


Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread David Sweeris via swift-evolution

> On Feb 19, 2017, at 21:19, Xiaodi Wu  wrote:
> 
> This is very, very interesting. Thank you so much for the text.
> 
> If I understand your take correctly, the benefits of `pure` in Swift would be 
> contingent on how pervasively it can be used (as it's the composability of 
> pure functions that gives it exponential value). And, based on your 
> discussion, very few functions in Swift would be compiler-provably pure [...]

I think this might, at least partly, be because we can't restrict generic 
parameters to be value types.

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


Re: [swift-evolution] A concern

2017-02-19 Thread Brent Royal-Gordon via swift-evolution
> On Feb 19, 2017, at 1:00 AM, Rien via swift-evolution 
>  wrote:
> 
> One of the big plusses of Objective-C was that the entire manual was just a 
> few pages long. I have not looked it up, but IIRC the entire manual 
> describing the language was probably less than 50 pages. Much less if you 
> subtract the filler stuff.

A couple people have pointed at least part of this out, but just to underline 
it:

"Objective-C" is able to be small only because it's sandwiched between C and 
Foundation, both of which are pretty big. A Swift book that discussed only 
non-generic classes and protocols without associated types would be pretty 
short, too.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] A concern

2017-02-19 Thread Kenny Leung via swift-evolution
I listened to this podcast, and it is fantastic - I’m going to listen to it 
again.

I used to have the same reservations about the directions that Swift was going 
in, but one thing Chris said in the podcast really changed my mind: the idea of 
progressively revealing complexity to the user.

At some level, if you want to do powerful things, you need to have powerful 
(and dangerous) tools. Since Chris’ goal for Swift is World Domination, it will 
eventually need to do everything. The important part is to do it in a measured 
way so that it’s easily approachable, yet you can peel back the complexity 
veils as you need to do more. That being said, I don’t think Swift has been 
doing a good job of this so far (String, Optionals, Generics)  But I have faith 
that the community on swift-evolution, (with temperance from the core team) 
will eventually mould the language into the ideal: keep simple things simple, 
make difficult things easy, make impossible things possible. It would be nice 
if this were “written into the constitution” of Swift.

-Kenny


> On Feb 19, 2017, at 1:24 AM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> I think it’s intended but in a good way. If you have missed the podcast with 
> Chris Lattner:
> 
> Podcast: http://atp.fm/205 
> Transcript: http://atp.fm/205-chris-lattner-interview-transcript/ 
> 
> Quote:
> 
> Obviously, I care a lot about Swift and I really want it to get to its goal 
> of world domination.
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 19. Februar 2017 um 10:02:04, Rien via swift-evolution 
> (swift-evolution@swift.org ) schrieb:
> 
>>  Swift seems to be on course to become a behemoth of a language. 
> 
> 
> ___
> 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] final + lazy + fileprivate modifiers

2017-02-19 Thread Jose Cheyo Jimenez via swift-evolution

> On Feb 19, 2017, at 7:29 PM, David Waite  wrote:
> 
> Swift 2’s access modifiers had a very simple ‘elevator pitch’ - 
> “If you are writing code, by default everything within the module (app or 
> library) your are working in can see it, but other modules cannot. If you 
> want other modules to see features of your module, you make them public. If 
> something is an implementation detail that even other parts of your module 
> shouldn’t mess with, you make them private”
> 
> I think I would have trouble *just* describing private vs file private in 
> that amount of space. One sign of the complexity was that even after a 
> ridiculous amount of bike shedding, we couldn’t come up with better way to 
> distinguish the two than to call one “fileprivate”. So I would say for the 
> purposes of swift as a language suitable for learning, the change was 
> harmful. 

Swift’s scope private is not different than other languages. 

> 
> Secondly, there are reasons to choose one versus the other, but the 
> combination of the meaning of the keyword changing between swift 2 and 3 and 
> the spelling of “fileprivate” means that the choice of one or the other 
> doesn’t really communicate anything to a developer of a typical project - it 
> appears to often be a matter of the legacy of the code as well as developer 
> taste. That the choice between private and file private doesn’t illustrate 
> intent is harmful to coordination.

This really depends on where private is. If it on the top scope then private is 
the same as file-private and your statement is correct. 

SE-0025 was changed to allow higher access modifier for inner types and this is 
when things started to get confusing because the vast majority of times when 
scope private was being used in reality is the same as fileprivate. The fact 
that we encourage the use of scope private over file-private is harmful because 
of the confusion. 


// File.swift

private let myString = ""   // fileprivate same as private
fileprivate let myString2 = ""  // fileprivate same as private


private struct MyType {  // fileprivate same as private
fileprivate struct MyInnerType{  // private never the same as private
fileprivate struct MyInnerType{} // private never the same as private
}
}

// end of File.swift



 
> 
> A third point (which is a bit more complex/convoluted) is that fileprivate 
> remained an essential language feature because it allows implementation in 
> extensions, and allows a simple “friend”-like feature where types that need 
> access to implementation details due to higher coupling could be bundled into 
> the same file. Outside of a desire of a scoped ‘private’ simply to match the 
> behavior of certain other languages, private is used to hide implementation 
> details from other parts of a file, while file private exposes them within 
> the file. 
> 
> There is a potential that file-private can lead to an explosion of complexity 
> due to a large amount of “friendly types” being bundled into the same file. 
> In that sense, ‘private’ was wrong because it was adding complexity at the 
> file level, when really a new access level would possibly have been more 
> productive to define at the at the small-group-of-files level - either via a 
> friend access level or submodules. We still have the potential of 
> unmanageable files due to friend types, but any additional access levels to 
> aid with this problem would have to be weighed against a now significantly 
> more complex access model including file and scoped private. In that sense, 
> the inclusion of scoped private may indeed be harmful in that it increases 
> the challenge of much more useful access levels being added to the language.
> 
> -DW
> 
>> On Feb 18, 2017, at 11:57 PM, Jose Cheyo Jimenez via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> How exactly is the use of scope private harmful? 
>> 
>> Do you have specific examples when scope private was harmful?
>> 
>> 
>> 
>>> On Feb 18, 2017, at 9:06 PM, Zach Waldowski via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> On Fri, Feb 17, 2017, at 07:52 PM, Jose Cheyo Jimenez via swift-evolution 
>>> wrote:
 I don’t think there is evidence that scope private in Swift3 is "actively 
 harmful”. 
 
>>> 
>>> This thread would quite simply not exist if not to present exactly that 
>>> evidence. It exists; we, the change's detractors, exist.
>>> 
>>> Zachary
>>> 
>>> ___
>>> 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] Guarded closures and `@guarded` arguments

2017-02-19 Thread Brent Royal-Gordon via swift-evolution
> On Feb 19, 2017, at 2:57 PM, Matthew Johnson via swift-evolution 
>  wrote:
> 
> A guarded closure may be created by prefixing a bound instance method 
> reference with the `?` sigil:
> 
> ```swift
> let guarded = ?myObject.myMethod
> 
> // desugars to:
> let guarded = { [weak myObject] in
>  guard let myObejct = myObject else {
>return
>  }
>  myObject.myMethod()
> }
> ```

I like this in principle, but I don't like the syntax. The `?` is cryptic and 
looks pretty strange in prefix position. I think what I'd like to see is:

let guarded = weak myObject.myMethod

Or:

let guarded = weak(myObject).myMethod

This second alternative could give us the opportunity to specify a default 
return value if we'd like:

let guarded = weak(myObject, else: nil).myMethod

> A guarded closure may be created by prefixing an inline closure with the `?` 
> sigil:
> 
> ```swift
> let guarded = ?{ flag in
>  flag ? someMethod() : someOtherMethod()
> }
> 
> // desugars to:
> let guarded = { [weak self] flag in
>  guard let strongSelf = self else {
>return
>  }
> 
>  flag ? strongSelf.someMethod() : strongSelf.someOtherMethod()
> ```

This runs into the same problem as previous suggestions for addressing the 
weak-strong dance: There's no particular reason to privilege this behavior over 
any other.

I think I'd prefer to use a slightly wordier two-part solution here:

1. If the capture list is just `[weak]` (or `[unowned]`), that's the 
default for all variables.

2. A `guard` with no condition—in other words, `guard else`—tries to 
strengthen all weakly captured variables and enters the `else` block if any 
fail. (Alternative: `guard let else`.)

That makes your example into:

let guarded = { [weak] flag in 
guard else { return }
flag ? self.someMethod() : self.someOtherMethod()
}

This is many more characters, but I think it's also much clearer about what's 
going on.

>  Self reference in escaping guarded closures
> 
> Guarded closures do not extend the lifetime of any objects unless a `strong` 
> capture is specified in the capture list.  Because this is the case users are 
> not required to explicitly reference self using the `self.` prefix inside a 
> guarded closure.

I think this is a bad idea, because the implicit `self` problem still exists 
here—it just has a slightly different shape. Here, if you accidentally use 
`self` without realizing it, your closure mysteriously doesn't get executed. 
This misbehavior is at least easier to notice, but it's still going to be hard 
to track down, since it's caused by something invisible in the code.

> ### `@guarded`
> 
> This proposal introduces the ability for arguments of function type to be 
> annotated with the `@guarded` attribute.  When `@guarded` is used the caller 
> must supply a guarded or non-capturing closure as an argument.  This ensures 
> that users of the API think very carefully before providing an argument that 
> captures a strong reference, and requires them to explictly state their 
> intent when they wish to do so.

Even in this modified form, I think this is a bad idea. The person writing the 
closure is the one who knows whether they want it to extend objects' lifetimes. 
The library author accepting the closure has no idea whether the objects the 
closure captures are models it needs or controllers it shouldn't keep—or, for 
that matter, models it shouldn't keep or controllers it needs.

If we really think that this is a serious problem, we should change `@escaping` 
closures to always capture weak unless they're explicitly told to capture 
strong and be done with it. If that sounds like a hare-brained idea, then we 
shouldn't do it half the time and not do it the other half.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Manifesto] Ownership

2017-02-19 Thread John McCall via swift-evolution
> On Feb 18, 2017, at 11:08 AM, Matthew Johnson  wrote:
> Hi John,
> 
> This is fantastic!  I’ve been eagerly anticipating this.  It looks very much 
> as I was hoping it would.  I can’t wait to see this vision come to life!
> 
> You only show a mutating generator example.  Do you also plan to allow shared 
> generators?

Yes; a generator yielding a shared reference would be used for non-mutating 
iteration.

> One topic you don’t touch on that feels related is the ability to use RAII 
> and rely on deferred deinit to ensure an owned resource isn’t released before 
> the scope exits.  I can imagine something like `defer let resource = 
> MyResource()`.  It may also be interesting to support “defer only” types to 
> force a compiler error where non-deferred use would be incorrect.  What do 
> you think?

My intuition is the use cases for this that I'm aware of are really a mis-use 
of values.  You might design an API that way in C++, where destructors are 
really the only language mechanism for injecting code into a function "later", 
but in Swift I think you would want to use either (1) a generalized accessor 
(if the protected resource could meaningfully be described as a single value) 
or (2) a callback that explicitly scopes what happens with the resource.

So e.g. if you wanted a Rust-style mutex API, you could do it like so:

moveonly struct Locked {
  var unlockedMemory: T { // probably not the best name
read {
  mutex.acquire()
  defer { mutex.release() } // There are reasons why I think this needs to 
be in a defer, but we can talk about them when we get to the detailed proposals 
for co-routines.  I'm still looking for a better language design.
  yield actualMemory // Recall that 'read' yields a shared value, so this 
doesn't implicitly copy.
}
nonmutating modify { // 'nonmutating' is a misnomer, but it's an existing 
misnomer.  Setters are 'mutating' methods by default and normally demand 
exclusive access to self, but we don't need that here because we're dynamically 
enforcing exclusive access to the memory, so all we need is shared access, and 
this is how we express that.
  mutex.acquire()
  defer { mutex.release() }
  yield &actualMemory
}
  }

  private var mutex: Mutex
  private mutable var actualMemory: T // Make this variable mutable even within 
nonmutating methods; whether that makes sense is the programmer's problem.  I 
didn't cover this in the proposal, because it's speculative, but it's useful 
for things like our nonmutating modify.  Lots of open questions here.
}

Or if you wanted a more C-like mutex API, you'd do it like so:

moveonly struct Mutex {
  func withLock(_ function: () throws -> T) rethrows -> T {
acquire()
defer { release() }
return try function()
  }
}

But I just don't see the motivation to try to do this by making a function 
return a C++-style lock guard.

Do you have a use case which clearly benefits from an exact scoping and really 
needs to be an independent value?

John.

> 
>> On Feb 17, 2017, at 11:08 AM, John McCall via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>>> On Feb 17, 2017, at 4:50 AM, Adrian Zubarev 
>>> mailto:adrian.zuba...@devandartist.com>> 
>>> wrote:
>>> Hi John, would you mind creating a markdown document for this manifesto in 
>>> https://github.com/apple/swift/tree/master/docs 
>>> ? :)
>>> 
>>> 
>> Yes, it should go in the repository.  That commit is pending, but the in 
>> meantime, you can see the document properly rendered at:
>>   
>> https://github.com/rjmccall/swift/blob/4c67c1d45b6f9649cc39bbb296d63663c1ef841f/docs/OwnershipManifesto.md
>>  
>> 
>> 
>> John.
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>> 
> 

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


Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread Xiaodi Wu via swift-evolution
This is very, very interesting. Thank you so much for the text.

If I understand your take correctly, the benefits of `pure` in Swift would
be contingent on how pervasively it can be used (as it's the composability
of pure functions that gives it exponential value). And, based on your
discussion, very few functions in Swift would be compiler-provably pure,
meaning any realistic adoption would have to mean "trust me, compiler, it's
pure even though you can't prove it" as opposed to "go ahead, compiler,
test my assertion that this function is pure." If Swift is to keep its
promise of safety by default (granted, principally memory safety), this is
going to have to prompt some soul-searching as to whether that's a very
safe thing to add. It would also mean that lots of things would have to be
manually annotated "trust me" after careful analysis of whether that trust
is warranted, as opposed to the compiler being able to work that out for
itself for free.

Can I venture an operational definition of semantic purity? Maybe this
would be a basis to talk about what "trust me, it's pure" would mean, if we
wanted it:

Consider two variables `a` and `b`, without regard to whether they are
instances of value types or reference types, and without regard to whether
those types are Equatable.

```
let aa = a
let bb = b
```

Let's define, only for the purposes of this discussion and not as an actual
syntax, a notion of pseudo-equality. We will say that `aa` is pseudo-equal
to `a` and `bb` is pseudo-equal to `b`. (I deliberately choose not to
conflate this notion with Equatable's `==` or with `===`.) Now, consider a
function `f(_:_:)`.

```
let result1 = f(a, b)
// ...
// arbitrary code to be executed here
// ...
let result2 = f(aa, bb)
```

The function `f(_:_:)` is pure if, for any `aa` pseudo-equal to `a` and for
any `bb` pseudo-equal to `b`, and for any arbitrary code in the middle, the
snippet above could be replaced by the snippet below with no observable
change in behavior:

```
let result1 = f(a, b)
// ...
// arbitrary code to be executed here
// ...
let result2 = result1
```

Now, this naive definition would preclude I/O and inout, but it would not
preclude infinite loops, fatal errors, etc.


On Sun, Feb 19, 2017 at 10:49 PM, Michel Fortin 
wrote:

> The message about D was from me. I'm actually quite familiar with D so
> I'll try to summarize it's take on purity here.
>
> # Pure in D
>
> D has the keyword `pure`, and the compiler enforces purity constraints.
> There is basically two types of pure functions: strongly pure ones and
> weakly pure one, but in general when writing code you can ignore the
> distinction: they all use the same `pure` attribute. The strongly pure one
> is the kind that can be optimized because it has no side effect and its
> result can be reused. The weakly pure one is the kind that takes pointers
> to non-immutable memory and for which you either cannot guaranty a stable
> result across calls or cannot guaranty it won't mutate the memory behind
> those pointers. (Keep in mind that object references are a kind of pointer
> too.) The compiler examine the type of the parameters of a pure function to
> determine if they contain pointers (including pointers hidden in structs)
> and classify it as weakly or strongly pure.
>
> Pure functions are allowed to throw, to exit the program, to run infinite
> loops, and to allocate memory. They can't access global variables unless
> they are immutable (constant), or they are passed as an argument using a
> pointer.
>
> All pure functions can only call other pure functions. This is the part
> where weakly pure is useful: a strongly pure function can call a weakly
> pure function since the weakly pure one will only be able to mutate the
> local state of the enclosing strongly pure function, always in a
> deterministic way.
>
> In D, `const` and `immutable` are transitive attributes, meaning that any
> memory accessed through such pointer is also `const` or `immutable`. So if
> you pass a `const` or `immutable` value to a function in D, it won't be
> able to mutate anything. This makes many functions strongly pure even in
> the presence of pointers.
>
> `pure` in D can also be used to create guarantied uniquely referenced
> objects and object hierarchies, which then can then become transitively
> immutable once they are returned by the pure function.
>
> `pure` works so well in D that most functions are actually pure. There is
> some pressure in libraries to mark functions as pure because their
> functions then become usable inside other pure functions, which means that
> as time passes more and more functions get the pure attribute. To ease the
> burden of adding these attributes everywhere, pure is inferred for template
> functions (and only template functions, because non templates are allowed
> to be opaque).
>
> Official reference: https://dlang.org/spec/function.html#pure-functions
>
> # Pure in Swift?
>
> Because Swift does not have that concept of

Re: [swift-evolution] [Draft] @selfsafe: a new way to avoid reference cycles

2017-02-19 Thread Brent Royal-Gordon via swift-evolution
> On Feb 19, 2017, at 7:06 PM, Matthew Johnson  wrote:
> 
> Often you hand it to something owned by self, but it's also the case that you 
> often hand it to something not owned by self, but that should not extend the 
> lifetime of self.

I don't agree that it shouldn't extend the lifetime of `self`. By default, 
Swift assumes that if you capture an object in a closure, you want that object 
to stay alive as long as the closure does.

I see absolutely no reason that this assumption should be different for `self` 
than it is for any other variable, and I see no reason to believe the caller 
would have a particularly good idea about this.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread Michel Fortin via swift-evolution
The message about D was from me. I'm actually quite familiar with D so I'll try 
to summarize it's take on purity here.

# Pure in D

D has the keyword `pure`, and the compiler enforces purity constraints. There 
is basically two types of pure functions: strongly pure ones and weakly pure 
one, but in general when writing code you can ignore the distinction: they all 
use the same `pure` attribute. The strongly pure one is the kind that can be 
optimized because it has no side effect and its result can be reused. The 
weakly pure one is the kind that takes pointers to non-immutable memory and for 
which you either cannot guaranty a stable result across calls or cannot 
guaranty it won't mutate the memory behind those pointers. (Keep in mind that 
object references are a kind of pointer too.) The compiler examine the type of 
the parameters of a pure function to determine if they contain pointers 
(including pointers hidden in structs) and classify it as weakly or strongly 
pure.

Pure functions are allowed to throw, to exit the program, to run infinite 
loops, and to allocate memory. They can't access global variables unless they 
are immutable (constant), or they are passed as an argument using a pointer. 

All pure functions can only call other pure functions. This is the part where 
weakly pure is useful: a strongly pure function can call a weakly pure function 
since the weakly pure one will only be able to mutate the local state of the 
enclosing strongly pure function, always in a deterministic way.

In D, `const` and `immutable` are transitive attributes, meaning that any 
memory accessed through such pointer is also `const` or `immutable`. So if you 
pass a `const` or `immutable` value to a function in D, it won't be able to 
mutate anything. This makes many functions strongly pure even in the presence 
of pointers.

`pure` in D can also be used to create guarantied uniquely referenced objects 
and object hierarchies, which then can then become transitively immutable once 
they are returned by the pure function.

`pure` works so well in D that most functions are actually pure. There is some 
pressure in libraries to mark functions as pure because their functions then 
become usable inside other pure functions, which means that as time passes more 
and more functions get the pure attribute. To ease the burden of adding these 
attributes everywhere, pure is inferred for template functions (and only 
template functions, because non templates are allowed to be opaque).

Official reference: https://dlang.org/spec/function.html#pure-functions

# Pure in Swift?

Because Swift does not have that concept of transitive immutability, I'm under 
the impression that very few functions would be "strongly pure" in Swift, 
making optimizations impossible except for the trivial value types. Or, maybe, 
when a "trust me" attribute vouch that the implementation of a value type is 
pure-compatible.

But I'd be wary about relying much on a "trust me" attribute, as it greatly 
diminish the value of having `pure` in the first place. Add a "trust me" at the 
wrong place and the compiler will not complain when it should. Forget a "trust 
me" somewhere and the compiler will complain where it should not. The ratio of 
"trust me"/`pure` has to be very small for the whole purity system to be 
valuable.

The way I see it, `pure` is likely to make things more complicated for 
everyone, not just for those who want to use pure. Those who want to use pure 
will be asking for everything they want to use to be labeled correctly (either 
with `pure` or "trust me", whichever works).

# What about constexpr?

That's the name of a C++ feature where the compiler evaluates a function at 
compile time to set the value of a constant. This obviously only works for 
functions with no side effects. `constexpr` is the keyword attached to those 
functions.
http://en.cppreference.com/w/cpp/language/constexpr

The difference from `pure` is that this happens only at compile time. Which 
means you can implement it like D has done instead: treat all functions as 
evaluatable and only stop and emit an error upon reaching an instruction that 
cannot be evaluated. No special attribute needed. Only works for functions 
where the source code is available.
https://dlang.org/spec/function.html#interpretation

The D approach won't work for Swift across module boundaries, except perhaps 
for functions that can be inlined. For resilience you might want an attribute 
to make it a contract that the inline version is compile-time evaluable.


Le 19 févr. 2017 à 20:58, Xiaodi Wu via swift-evolution 
 a écrit :
> 
> I don't know very much about this topic, so I won't pretend that I have 
> strong feelings about Michel's questions, but they are undeniably important 
> and undoubtedly only one of many.
> 
> Before we get to any syntactic bikeshedding, can the proponents of this 
> feature write up a comparative summary to educate us about the current state 
> of the a

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Zach Waldowski via swift-evolution
On Sun, Feb 19, 2017, at 10:57 PM, Xiaodi Wu via swift-evolution wrote:
> Left unsaid from my reply about enums is that implicit conversions
> should absolutely be added. We already have this magic for one
> particular enum, Optional.


I can only see a generalization of this being used for evil.
Perhaps that's best left to be discussed on some other knock-down,
drag-out thread.


> I'm not arguing with you that enums are currently unsuitable. In fact
> I entirely agree. But Chris Lattner and others have said (now I'm
> paraphrasing, but I believe accurately) that they *should* be. What
> will it take? At minimum, some way to opt into implicit conversions.
> It's a no-brainer in my mind.
> 

> Bottom line: the language needs one excellent way to model Foo | Bar |
> Baz, not two or three mediocre workarounds. The core team has said
> that they want that excellence to be built through enums. Let's do it.


I don't understand how extending protocols to parallel the changes we
already made to classes — and in line with what's planned for enums — is
a mediocre workaround.


I have low confidence in Evolution being able to produce a passable
union type design in a meaningful amount of time, particularly for Swift
4 Phase 2; I also question their need in the first place.


Sincerely,

  Zachary Waldowski

  z...@waldowski.me


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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Feb 19, 2017, at 9:57 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> Left unsaid from my reply about enums is that implicit conversions should 
> absolutely be added. We already have this magic for one particular enum, 
> Optional.

+1.  I cover a design to enable this in my value subtyping manifesto.

> 
> I'm not arguing with you that enums are currently unsuitable. In fact I 
> entirely agree. But Chris Lattner and others have said (now I'm paraphrasing, 
> but I believe accurately) that they *should* be. What will it take? At 
> minimum, some way to opt into implicit conversions. It's a no-brainer in my 
> mind.
> 
> Bottom line: the language needs one excellent way to model Foo | Bar | Baz, 
> not two or three mediocre workarounds. The core team has said that they want 
> that excellence to be built through enums. Let's do it.

I would love to hear your thoughts on my value subtyping manifesto which covers 
a plethora of enum enhancements, including everything relevant to and discussed 
in this thread.

That said, there are cases where enums are not appropriate and a closed 
protocol is more appropriate.  Specifically when the set of types is expected 
to evolve over time or is large enough that an enum is a bit unwieldy, but is 
still intended to be controlled by the library.  In these cases you may well 
prefer to use polymorphism rather than switch statements in the implementation. 
 

I see no reason to have "one true way".  Each approach has pros and cons.  An 
engineering tradeoff is required.  The fact that one solution may be the most 
appropriate in the majority of cases is no reason to preclude the alternative 
from being available.  It may be the better choice in a nontrivial minority of 
cases, which is plenty frequently enough to justify its availability.

> 
> 
>> On Sun, Feb 19, 2017 at 21:28 Zach Waldowski via swift-evolution 
>>  wrote:
>>> On Sun, Feb 19, 2017, at 06:40 PM, Xiaodi Wu via swift-evolution wrote:
>> 
>>> On Sun, Feb 19, 2017 at 5:15 PM, Brent Royal-Gordon via swift-evolution 
>>>  wrote:
>>> What is the harm of permitting an outside conformance to `SQLiteValue`?
>> 
>> 
>> I'll put words in Brent's mouth here as an attempt at an answer: you 
>> sometimes need to exclusively switch a downcast of an existential. Consider 
>> a serialization type - or SQLiteValue - where need to treat specific 
>> fundamental types ("primitives") in implementation-dependent ways. In a 
>> theoretical serialization design, all non-primitives would have an explicit 
>> protocol of semantics to conform to support serialization, much like the 
>> stdlib's "Custom" protocol pattern, and you compose from there.
>> 
>> Using an enum to represent this exclusivity remains unconvincing to me, 
>> unless we choose to add implicit conversions to the language. `.int(42)` is 
>> an overwhelming level of duplicate type information in any practical, 
>> non-trivial use case. Yes, (closed) enums model exclusivity. They are not 
>> the only things to do so.
>> 
>> The stdlib alone is reason enough for this feature to exist, even if not 
>> exposed publicly.
>> 
>> Zachary
>> 
>> ___
>> 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] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
Left unsaid from my reply about enums is that implicit conversions should
absolutely be added. We already have this magic for one particular enum,
Optional.

I'm not arguing with you that enums are currently unsuitable. In fact I
entirely agree. But Chris Lattner and others have said (now I'm
paraphrasing, but I believe accurately) that they *should* be. What will it
take? At minimum, some way to opt into implicit conversions. It's a
no-brainer in my mind.

Bottom line: the language needs one excellent way to model Foo | Bar | Baz,
not two or three mediocre workarounds. The core team has said that they
want that excellence to be built through enums. Let's do it.


On Sun, Feb 19, 2017 at 21:28 Zach Waldowski via swift-evolution <
swift-evolution@swift.org> wrote:

> On Sun, Feb 19, 2017, at 06:40 PM, Xiaodi Wu via swift-evolution wrote:
>
> On Sun, Feb 19, 2017 at 5:15 PM, Brent Royal-Gordon via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> What is the harm of permitting an outside conformance to `SQLiteValue`?
>
>
> I'll put words in Brent's mouth here as an attempt at an answer: you
> sometimes need to exclusively switch a downcast of an existential. Consider
> a serialization type - or SQLiteValue - where need to treat specific
> fundamental types ("primitives") in implementation-dependent ways. In a
> theoretical serialization design, all non-primitives would have an explicit
> protocol of semantics to conform to support serialization, much like the
> stdlib's "Custom" protocol pattern, and you compose from there.
>
> Using an enum to represent this exclusivity remains unconvincing to me,
> unless we choose to add implicit conversions to the language. `.int(42)` is
> an overwhelming level of duplicate type information in any practical,
> non-trivial use case. Yes, (closed) enums model exclusivity. They are not
> the only things to do so.
>
> The stdlib alone is reason enough for this feature to exist, even if not
> exposed publicly.
>
> Zachary
>
> ___
> 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] open and public protocols

2017-02-19 Thread David Waite via swift-evolution

> On Feb 19, 2017, at 1:14 AM, Adrian Zubarev  
> wrote:

> Here is a list of hidden and semi-hidden protocols from the standard library 
> that could be closed. Formatted version: 
> https://gist.github.com/DevAndArtist/168c800d784829be536c407311953ab7 
> The 
> majority of this list seems to more likely be non-resilient, appropriate to 
> be hidden rather than being closed. Several of these I believe only exist due 
> to features which are not yet in the Swift language, such as conditional 
> conformances and generalized existentials.

The types in the standard library which I think are relevant to a 
closed-protocol/union-type discussion would be:

CVarArg - interface of types appropriate to withVaList. “Closed” nature already 
enforced by compiler, e.g.;
class FooBar : CVarArg {} //error: type 'FooBar' does not conform to protocol 
‘CVarArg’

AFAICT, there is no reason that a third party type *couldn’t* implement 
CVarArg, other than the requirements of the protocol being considered private 
to the standard library (and possibly non-resilient). A valid protocol 
implementation returns the data (as an [Int] array) that is to be appended to 
the va_list.

MirrorPath - conceptually very similar to the SubscriptParameter, supporting 
String, Int and IntMax types. While the protocol is not closed, 
Mirror.descendent will preconditionFail if a different type other than String, 
Int, or IntMax is passed in.

-DW
 
> 
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 19. Februar 2017 um 07:59:45, David Waite via swift-evolution 
> (swift-evolution@swift.org ) schrieb:
> 
>> I am unsure if this feature is a good idea. Does someone have a real-world 
>> use for this which isn’t just hiding strong implementation coupling behind a 
>> protocol?
>> 
>> When I consume a protocol, it is under the assumption that the protocol is 
>> documented such that I would be able to work against *any* implementation of 
>> the protocol. With a closed protocol, I would have to assume that there are 
>> significant side effects, either undocumented or difficult for a third party 
>> to duplicate. To my experience, that sounds brittle.
>> 
>> Assuming you aren’t switching on the implementing type of a protocol (which 
>> itself can be a sign that your design isn’t properly using polymorphism), 
>> one could get this design by creating a struct with the interface desired, 
>> and passing invocations through to an internal protocol reference.
>> 
>> -DW
>> 
>> > On Feb 18, 2017, at 1:41 PM, Matthew Johnson via swift-evolution 
>> >  wrote:
>> > 
>> > Now that we’re in phase 2 I’d like to officially propose we introduce 
>> > `open` protocols and require conformances to `public` protocols be inside 
>> > the declaring module. Let’s use this thread for feedback on the official 
>> > proposal. After a healthy round of discussion I’ll open a PR to submit it 
>> > for review.
>> > 
>> > 
>> > # Feature name
>> > 
>> > * Proposal: [SE-](-open-public-protocols.md)
>> > * Authors: [Matthew Johnson](https://github.com/anandabits)
>> > * Review Manager: TBD
>> > * Status: **Awaiting review**
>> > 
>> > ## Introduction
>> > 
>> > This proposal introduces `open protocol` and changes the meaning of 
>> > `public protocol` to match the meaning of `public class` (in this case, 
>> > conformances are only allowed inside the declaring module).
>> > 
>> > The pitch thread leading up to this proposal was: [consistent public 
>> > access 
>> > modifiers](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170206/031653.html)
>> > 
>> > ## Motivation
>> > 
>> > A general principle the Swift community has adopted for access control is 
>> > that defaults should reserve maximum flexibility for a library. The 
>> > ensures that any capabilities beyond mere visibility are not available 
>> > unless the author of the library has explicitly declared their intent that 
>> > the capabilities be made available. Finally, when it is possible to switch 
>> > from one semantic to another without breaking clients (but not vice-versa) 
>> > we should prefer the more forgiving (i.e. fixable) semantic as the (soft) 
>> > default.
>> > 
>> > `public` is considered a "soft default" in the sense that it is the first 
>> > access modifier a user will reach for when exposing a declaration outside 
>> > of the module. In the case of protocols the current meaning of `public` 
>> > does not meet the principle of preserving maximum flexibility for the 
>> > author of the library. It allows users of the library to conform to the 
>> > protocol.
>> > 
>> > There are good reasons a library may not wish to allow users to add 
>> > conformances to a protocol. For example, it may not wish to expose the 
>> > conforming concrete types. While similar behavior could be accomplished 
>> > with an enum if cases could be private, that requires an implemen

Re: [swift-evolution] A concern

2017-02-19 Thread Slava Pestov via swift-evolution

> On Feb 19, 2017, at 1:00 AM, Rien via swift-evolution 
>  wrote:
> 
> Hello All,
> 
> Its Sunday, time for some reflection...
> 
> One of the big plusses of Objective-C was that the entire manual was just a 
> few pages long. I have not looked it up, but IIRC the entire manual 
> describing the language was probably less than 50 pages. Much less if you 
> subtract the filler stuff.

If you add the size of the C specification, Objective-C is actually a very 
large language, with all kinds of quirks and undefined behavior. Most people 
coming to Objective-C already have some familiarity with C-like languages 
though, so I think this aspect is forgotten sometimes.

> I have been on this list now for a few weeks, and I see very little push-back 
> on new suggestions. Most of the reactions are positive-constructive. IMO we 
> need more push-back. Without it behemoth status is all but guaranteed.
> 
> I don’t know about the core team, I don’t know about Apple, I don’t know 
> where they want to go.

I think it is good and healthy that all kinds of outlandish ideas get discussed 
on this list; even if they never end up getting implemented — the discussions 
further mutual understanding and inspire better ideas in the future. It 
wouldn’t be productive for us to just unilaterally shut down such discussions.

Remember there’s a long road from “pitching an idea” to “core team accepts a 
proposal”. The bar for proposals accepted into Swift 4 is considerably higher; 
think of it as, “without this proposal, the language is fundamentally broken 
for an important use-case”.

Also I think one important quality of the Swift design is “progressive 
disclosure”. There are some advanced features, but they are layered on in such 
a way that one does not need to absorb most of them in order to be productive 
in the language. They can be learned over time. This is unlike, say, C++, where 
a lot of complexity has to be understood up-front before you can really write 
good modern C++.

It’s not necessarily a bad thing if a well-designed language with advanced 
features and a large standard library has a big manual.

> I just want to make a plea here: Please stop Swift from becoming a behemoth.

As someone who admires small languages like Scheme, Smalltalk, Forth and ML, I 
can assure you that your point of view has its proponents here ;-) And I think 
the core team has very good taste when it comes to these things as well.

Slava

> 
> I don’t know if the millions (?) of Swift developers not on this list agree 
> with me. I somehow think they do, after all they are not on this list! They 
> are not looking to change Swift...
> 
> Well, I just had to get that off my chest...
> 
> To close this off, I do want to take this opportunity to thank the core team 
> for their work, I truly appreciate it!
> And whatever may come, here is one happy Swift user!
> 
> Best regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl
> 
> 
> 
> 
> 
> ___
> 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] open and public protocols

2017-02-19 Thread David Waite via swift-evolution

> On Feb 19, 2017, at 4:18 PM, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> On Sun, Feb 19, 2017 at 5:10 PM, Adrian Zubarev 
> mailto:adrian.zuba...@devandartist.com>> 
> wrote:
> Because someInstance["key", .string("key1"), .integer(1), 
> .string(stringKeyInstance), .integer(intIndexInstance), 
> .integer(intIndexInstance), …] is simply ugly and should be hidden. Such API 
> looks horrible.
> 
> I agree. This cries out for improvements to enums. Indeed, I have run into 
> the same issue with this and have a proposal idea saved up regarding 
> anonymous enum cases and subtyping relationships. It would not have been 
> in-scope for phase 1, so I did not write to the list about it. I'm short on 
> time these days, but eventually I'll propose it unless someone else gets to 
> it first. However, this problem does not justify `open` vs. `public`.

Agreed, if the use case is meant for working around the lack of union types, we 
should be very careful in deciding whether the fix should be:
1. Making enums syntactically better for representing union types
2. Adding union types to the language proper, distinct from enums
3. Using a type (such as a closed protocol) to ‘tag’ members of a union type
4. Propose the SubscriptParameter pattern given before as ‘the’ way to solve 
this problem.

Are closed protocols a quick fix or the pattern going forward?

-DW

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


Re: [swift-evolution] final + lazy + fileprivate modifiers

2017-02-19 Thread David Waite via swift-evolution
Swift 2’s access modifiers had a very simple ‘elevator pitch’ - 
“If you are writing code, by default everything within the module (app or 
library) your are working in can see it, but other modules cannot. If you want 
other modules to see features of your module, you make them public. If 
something is an implementation detail that even other parts of your module 
shouldn’t mess with, you make them private”

I think I would have trouble *just* describing private vs file private in that 
amount of space. One sign of the complexity was that even after a ridiculous 
amount of bike shedding, we couldn’t come up with better way to distinguish the 
two than to call one “fileprivate”. So I would say for the purposes of swift as 
a language suitable for learning, the change was harmful. 

Secondly, there are reasons to choose one versus the other, but the combination 
of the meaning of the keyword changing between swift 2 and 3 and the spelling 
of “fileprivate” means that the choice of one or the other doesn’t really 
communicate anything to a developer of a typical project - it appears to often 
be a matter of the legacy of the code as well as developer taste. That the 
choice between private and file private doesn’t illustrate intent is harmful to 
coordination.

A third point (which is a bit more complex/convoluted) is that fileprivate 
remained an essential language feature because it allows implementation in 
extensions, and allows a simple “friend”-like feature where types that need 
access to implementation details due to higher coupling could be bundled into 
the same file. Outside of a desire of a scoped ‘private’ simply to match the 
behavior of certain other languages, private is used to hide implementation 
details from other parts of a file, while file private exposes them within the 
file. 

There is a potential that file-private can lead to an explosion of complexity 
due to a large amount of “friendly types” being bundled into the same file. In 
that sense, ‘private’ was wrong because it was adding complexity at the file 
level, when really a new access level would possibly have been more productive 
to define at the at the small-group-of-files level - either via a friend access 
level or submodules. We still have the potential of unmanageable files due to 
friend types, but any additional access levels to aid with this problem would 
have to be weighed against a now significantly more complex access model 
including file and scoped private. In that sense, the inclusion of scoped 
private may indeed be harmful in that it increases the challenge of much more 
useful access levels being added to the language.

-DW

> On Feb 18, 2017, at 11:57 PM, Jose Cheyo Jimenez via swift-evolution 
>  wrote:
> 
> How exactly is the use of scope private harmful? 
> 
> Do you have specific examples when scope private was harmful?
> 
> 
> 
>> On Feb 18, 2017, at 9:06 PM, Zach Waldowski via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> On Fri, Feb 17, 2017, at 07:52 PM, Jose Cheyo Jimenez via swift-evolution 
>> wrote:
>>> I don’t think there is evidence that scope private in Swift3 is "actively 
>>> harmful”. 
>>> 
>> 
>> This thread would quite simply not exist if not to present exactly that 
>> evidence. It exists; we, the change's detractors, exist.
>> 
>> Zachary
>> 
>> ___
>> 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] [Draft] open and public protocols

2017-02-19 Thread Zach Waldowski via swift-evolution
On Sun, Feb 19, 2017, at 06:40 PM, Xiaodi Wu via swift-evolution wrote:
> On Sun, Feb 19, 2017 at 5:15 PM, Brent Royal-Gordon via swift-
> evolution  wrote:
>> What is the harm of permitting an outside conformance to
>> `SQLiteValue`?


I'll put words in Brent's mouth here as an attempt at an answer: you
sometimes need to exclusively switch a downcast of an existential.
Consider a serialization type - or SQLiteValue - where need to treat
specific fundamental types ("primitives") in implementation-dependent
ways. In a theoretical serialization design, all non-primitives would
have an explicit protocol of semantics to conform to support
serialization, much like the stdlib's "Custom" protocol pattern, and you
compose from there.


Using an enum to represent this exclusivity remains unconvincing to me,
unless we choose to add implicit conversions to the language. `.int(42)`
is an overwhelming level of duplicate type information in any practical,
non-trivial use case. Yes, (closed) enums model exclusivity. They are
not the only things to do so.


The stdlib alone is reason enough for this feature to exist, even if not
exposed publicly.


Zachary


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


Re: [swift-evolution] Dictionary Enhancements

2017-02-19 Thread Nate Cook via swift-evolution
> On Feb 19, 2017, at 6:13 PM, Ben Cohen via swift-evolution 
>  wrote:
> 
>> On Feb 19, 2017, at 11:22 AM, Ole Begemann > > wrote:
>> 
>>> On 17 Feb 2017, at 01:26, Ben Cohen via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> Here is a list of commonly requested changes/enhancements to Dictionary, 
>>> all of which would probably be appropriate to put together into a single 
>>> evolution proposal:
>>> 
>>> init from/merge in a Sequence of Key/Value pairs (already raised as SE-100: 
>>> https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md
>>>  
>>> ).
>>> make the Values view collection a MutableCollection (as in this PR: 
>>> https://github.com/apple/swift-evolution/pull/555 
>>> ).
>>> Add a defaulting subscript get (e.g. counts[key, default: 0] += 1 or 
>>> grouped(key, default:[]].append(value)).
>>> Add a group by-like init to create a Dictionary from a sequence of V 
>>> and a closure (V)->K.
>> Out of interest, how would you implement this? Does it require a generics 
>> feature that's slated for Swift 4? I tried two approaches that don't compile 
>> in a current Swift 3.1 snapshot (and I'm getting a segfault with both 
>> examples in a dev snapshot from 2017-02-14):
>> 
>> 1)
>> 
>> extension Dictionary {
>> // error: same-type constraint 'Value' == '[S.Iterator.Element]' is 
>> recursive
>> init(values: S, groupedBy: (S.Iterator.Element) -> Key)
>> where Value == [S.Iterator.Element] {
>> ...
>> }
>> }
>> }
>> 
>> 2)
>> 
>> // error: reference to generic type 'Array' requires arguments in <...>
>> extension Dictionary where Value == Array {
>> init(values: S, groupedBy: (S.Iterator.Element) -> Key)
>> where S.Iterator.Element == Value.Element {
>> ...
>> }
>> }
>> }

I don't totally have my head around this, but won't a Dictionary initializer 
like this require parameterized extensions as described in the generics 
manifesto? 

https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#parameterized-extensions

Something like this:

extension Dictionary where Value == [T] {
init(_ values: S, groupedBy: (S.Iterator.Element) -> Key) 
where S.Iterator.Element == T 
{ ... }
}

For what it's worth, I had been expecting that we'd add this as a method on 
Sequence, a la joined(by:), not an initializer.

extension Sequence {
func grouped(by grouping: (Iterator.Element) -> Key) 
-> [Key: [Iterator.Element]] 
{ ... }
}
let d = (1...10).grouped(by: { $0 % 3 })
// [2: [2, 5, 8], 0: [3, 6, 9], 1: [1, 4, 7, 10]]

Nate

> Oops, looks like a bug in the same-type constraint implementation. Ought to 
> work in 3.1. Minimal crasher repro:
> 
> extension Array {
>   func f() 
>   where Element == S.Iterator.Element? {
> 
>   } 
> }
> 
> I’ve raised https://bugs.swift.org/browse/SR-4008 
> 
> 
> It ought to be done with the first one. For the second, you can’t constrain 
> Value == Array because Array isn’t a type, needs to be Array.
> 
> As an (impractical) workaround, this compiles:
> 
> extension Dictionary {
> subscript(k: Key, default default: Value) -> Value {
> get { return self[k] ?? `default` }
> set { self[k] = newValue }
> }
> }
> 
> extension Dictionary where Value: RangeReplaceableCollection {
> init(grouping values: S, by: (S.Iterator.Element) -> Key)
> where S.Iterator.Element == Value.Iterator.Element {
> self = [:]
> for x in values {
> let k = by(x)
> self[k, default: Value()].append(x)
> }
> }
> }
> 
> 
> let s = [10,20,22,30,31]
> // have to explicitly type the Dictionary as a specific RRC
> let d: [Int:[Int]] = Dictionary(grouping: s) { $0%10 }
> 
> print(d)
> 
> 
> ___
> 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] @selfsafe: a new way to avoid reference cycles

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

On Feb 19, 2017, at 6:30 PM, Brent Royal-Gordon  wrote:

>> On Feb 19, 2017, at 6:45 AM, Matthew Johnson  wrote:
>> 
>> 1. Swift *already* acknowledges that it is far easier to create a reference 
>> cycle through captured strong references to `self` than any other way.  This 
>> is why you have to explicitly say `self.` in escaping closures.
> 
> The reason you have to explicitly say `self` is that `self` is the only 
> variable you can implicitly reference. That's disabled in closures, so it's 
> on the same footing as other variables.

It's only disabled in escaping closures, not all closures.  It is disabled 
there specifically because capturing it can produce a reference cycle.  But I 
agree, while it is by far the most frequent source of cycles it is not the only 
way to create them and a more general approach is better.

> 
> Other than that, the only reason `self` is more likely to cause a loop is 
> that, in common Cocoa patterns, you're more likely to be handing the closure 
> to something owned by `self`. But that's not *necessarily* the case, it just 
> happens to be true in many cases.

Often you hand it to something owned by self, but it's also the case that you 
often hand it to something not owned by self, but that should not extend the 
lifetime of self.  In that case you don't necessarily create a cycle but you do 
create what is effectively a leak.  In both cases getting a callback after self 
should have been released can lead to very bad things happening.

The reason self is somewhat unique is that usually when you pass a callback to 
something the implementation of the callback either modified instance state or 
calls methods on instance properties.  Occasionally you also capture an 
argument to the function that registers the callback or connect a method on 
some other object, but those are far less frequent than starting with your own 
instance state.  The majority of the time you do need to capture self and much 
of the time you don't need to capture any other references.  This is (IMO) why 
self is somewhat special and why API designs like target / action (which only 
allow "capture" of a single object) work very well.

> 
>> 2. There are *already* APIs which are designed to capture an object weak and 
>> then call a method on it if it's still around when an event occurs.  In fact 
>> this has been a trend in Apple's newer APIs.  Users are able to learn the 
>> semantics of these APIs without a problem.  In fact, users like the, because 
>> they solve a real problem by ensuring that3.  object lifetime is not 
>> extended when using them.
>> 
>> 3. Swift libraries don't tend to design APIs with weak callback semantics, 
>> probably because they are currently syntactically heavy for both users and 
>> libraries.  This is true even when weak callback semantics would be 
>> beneficial for users and help prevent leaks (which can lead to crashes and 
>> other badly behaved apps).
>> 
>> 4. There have been several ideas proposed to make weak capture easier to do 
>> on the call side but they haven't gone anywhere.  The syntactic savings 
>> aren't that significant for callers and the burden is still on callers to 
>> get it right.
> 
> I definitely agree this is a problem, but again, that doesn't mean `self` is 
> the issue here. I think this is mainly because (a) the pattern isn't taught, 
> and (b) there are some minor speed bumps in current Swift (like the inability 
> to shadow `self` in a closure parameter list).

I agree that self isn't the problem.  The biggest problem is that callback APIs 
that feel Swifty (i.e. just take a function) place the burden of not extending 
the lifetime of object references on the callee.  It is pretty rare to actually 
want a callback API to extend the lifetime of an object that you need to use 
when you are callback.  

In other words, for this class of API there is a significant limitation in the 
language that makes correct usage much more difficult than it should be.

I feel pretty good about the design I came up with for guarded closures.  This 
allows us to flip the default capture in a closure from strong to guarded (a 
new kind of capture) by using the `?` sigil (while still allowing explicit 
strong capture in the capture list).  APIs are allowed to use the `@guarded` 
argument annotation to require users to provide a guarded closure.  This means 
that they must be used with defaults that make sense for their use case while 
still giving users an easy way to change those defaults if necessary.

> 
>> If users actually need a strong reference there are ways to handle that.  
>> First, if it is likely that a user might want self to be captured strong the 
>> API might choose to not use `@selfsafe`.
> 
> This doesn't work. The API designer doesn't know what's at the call site, and 
> the user can't modify the API to suit the use.
> 
>> If they *do* choose to use it the could also add an overload that does not 
>> use it and

Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread Xiaodi Wu via swift-evolution
I don't know very much about this topic, so I won't pretend that I have
strong feelings about Michel's questions, but they are undeniably important
and undoubtedly only one of many.

Before we get to any syntactic bikeshedding, can the proponents of this
feature write up a comparative summary to educate us about the current
state of the art? How have other languages have defined purity? I recall an
earlier message about D, and some rough comparisons or non-comparisons to
C++ constexpr. Roughly, it would be very helpful to get some sense of the
following:

What other C-family languages have a concept of purity?

How is purity defined in those languages?

What use cases are enabled by those definitions of purity, and just as
important, what use cases are notably excluded by them?

If there is evidence in the public record to this effect: if the designers
of those languages could do it again, have they expressed any thoughts
about how they would do it differently with respect to purity?

It has been said that Haskell and other functional languages prioritize
purity over ergonomics of impure functions like I/O. With that in mind,
what design choices surrounding purity made by those languages are
off-limits for Swift?

What use cases or even compiler optimizations are possible in Haskell and
other non-C family languages with a more expansive or stricter concept of
pure functions that we don't find in C-family languages?

If Swift were to adopt some of these beyond-C rules, how would that impact
the user experience with common impure functions (I/O, etc.)?

On Sun, Feb 19, 2017 at 14:45 T.J. Usiyan via swift-evolution <
swift-evolution@swift.org> wrote:

> I'm going to update the draft with points addressed here and the twitter
> conversation. There have been quite a few implications to consider pointed
> out.
>
> This feature is not 'for' the compiler as much as it is for humans writing
> code, but I will address that in the update.
>
> On Sun, Feb 19, 2017 at 3:34 PM, David Sweeris 
> wrote:
>
>
> On Feb 19, 2017, at 11:47, Michel Fortin via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> 7. Is it desirable that the optimizer sometime take the pure attribute to
> heart to combine multiple apparently redundant calls into a single one? Or
> is pure not intended to be usable for compiler optimizations? The ability
> to optimize will likely be affected by the answer to these question and the
> loopholes you are willing to allow.
>
>
> AFAIK, "compiler optimizations" are main point of having a keyword for
> pure functions. (Well, that and whatever role it might play in supporting
> constant expressions, but that seems like more of a compiler implementation
> detail than an actual "feature" of pure functions.)
>
> Calling fatalError() is fine IMHO because, at that point, any side-effects
> become a moot point.
>
> I'm inclined to say that passing in reference values is ok, as long as we
> can prove the function doesn't modify anything. Don't know how we'd do
> that, though, since classes don't need that `mutating` keyword for
> functions that mutate `self`.
>
> If someone is determined to use pointers to pointers to get global state
> or something to trick the compiler into accepting *semantically* impure
> code as *syntactically* pure, I'm not sure there's a way we can really
> stop them. Not and still have @pure be useful. (Or maybe we can... I'm
> merely thinking of the saying, "every time someone builds a fool-proof
> system, the world makes a bigger fool".)
>
> I would think that allocating memory is ok, as long as it's either
> deallocated by the time the function exits or it's part of the return
> value, but I don't know a lot about low-level implementation details, so
> maybe there's something I'm missing. If that is a problem, though, I think
> the answer to your "what subset..." question would, more or less, be
> whatever subset doesn't rely on the runtime (the usefulness of that subset
> should expand if/when we extend the syntax around tuples or support
> fixed-length arrays in some other way).
>
> In any case, yeah, IMHO you're correct that we should nail down the
> semantics before worrying so much about the syntax.
>
> - 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] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Feb 19, 2017, at 6:52 PM, Daniel Duan  wrote:
> 
> 
>>> On Feb 19, 2017, at 11:49 AM, Matthew Johnson via swift-evolution 
>>>  wrote:
>>> 
>>> 
>>> On Feb 18, 2017, at 10:49 PM, Dave Abrahams via swift-evolution 
>>>  wrote:
>>> 
>>> I'm on vacation and don't have time for a full review right now, but I am 
>>> concerned that wild this proposal would make enums more general and uniform 
>>> with the rest of the language , they also would become much more awkward 
>>> for common use cases. I have recently been very pleased that I didn't have 
>>> to supply labels in switch statements where the label name would simply 
>>> have matched the name of the variable to be bound.  This looks needlessly 
>>> verbose:
>>> 
>>>   case .valid(value: let value, resumptionPoint: let resumptionPoint):
>>> 
>>> I cannot imagine a real life use case where one would have labels in the 
>>> case and desire to bind associated values to variables having different 
>>> names than the labels.
>> 
>> I agree with this, but I think it’s an issue we can solve (perhaps as an 
>> amendment to this proposal).
>> 
>> First, I think Brent’s idea of introducing an argument label that can be 
>> distinct from the “property” name of the case is a good one.  I think we 
>> should do this.  It takes the parallel with function signatures even further.
>> 
>> Second, we should allow the “property” name to be `_`.  This would mean no 
>> label can be used when matching:
>> 
>> case valid(value _: ValueType, resumptionPoint _: PointType)
>> 
>> Third, I think we should also allow suers to elide the label if they either 
>> discard the value with `_` or bind a name that is identical to the label, so 
>> we might have:
>> 
>> // declaration:
>> case valid(externalCasConstructorLabel value: ValueType, 
>> externalCaseConstructorLabel resumptionPoint: PointType)
>> 
>> // match ok:
>> case .valid(let value, let resumptionPoint):
>> 
>> // error, names do not match:
>> case .valid(let foo, let bar):
>> 
>> // ok, label is used:
>> case .valid(value: let foo, resumptionPoint: let bar):
>> 
>> This follows the behavior of function signatures very closely.  The external 
>> label is used to provide context for the argument at the call site (of the 
>> case constructor).  The internal name is used to bind a name to the value 
>> that is used by code that works with the value.  
>> 
>> The only exception here is that because the usage site is distant from the 
>> case declaration it may wish to use a different name.  We allow that, but 
>> only if the “internal name” is also used in the pattern.  This preserves the 
>> ability of a reader of the code to see the name / meaning of the associated 
>> value as it was declared by the enum in addition to the name that might make 
>> more sense for use in the local context.
>> 
>>> 
>>> Secondly, I can't imagine a case where one would want to use the same case 
>>> basename and different labels. The very common use case where the types of 
>>> associated values completely distinguish the case and one would rather not 
>>> have to supply a case name at all is completely unaddressed. If my quick 
>>> read is not mistaken, this proposal makes it legal for cases to have 
>>> different complete names (including base name and labels), but doesn't make 
>>> it legal to have the same full name (which I would love to be "_" or 
>>> missing in some cases) with different associated value types. If we were 
>>> truly following the precedent set by function signatures, wouldn't that be 
>>> possible too?
>> 
>> +1.  I think this makes a lot of sense.  It completes the parallel of cases 
>> with overloaded functions.
>> 
>> I think anonymous cases are a really good idea.  I discuss those quite a bit 
>> in the value subtyping manifesto I shared last week (I’d love to hear your 
>> thoughts on it if / when you have time to take a look).
>> 
>> How would you propose that values of anonymous cases be constructed and 
>> matched?  My solution is to allow them to be constructed by implicit 
>> conversion from the associated value type to the enum type and matched by a 
>> cast pattern.  Is that what you have in mind?  I would *really* love to see 
>> this someday...
> 
> I can’t speak for Dave obviously. But I think he was merely proposing 
> “overloaded” form of enum options, in which multiple options may share the 
> compound name but with differently associated types. The name “_” would just 
> be a normal identifier in such scenario. So it would also be the contractor’s 
> function name.

So values would be constructed like MyEnum._(42) and matched like ._(let i as 
Int).  Is that what you're thinking?  I suppose that would be a reasonable step 
to take for now.  Making MyEnum a subtype of the case types still seems like a 
more elegant long term goal.

> 
>>> 
>>> Sent from my moss-covered three-handled family gradunza
>>> 
 On Feb 17, 2017, at 5:26 PM, John McCall  wrote:
 
 Hello Swift 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Daniel Duan via swift-evolution

> On Feb 19, 2017, at 11:49 AM, Matthew Johnson via swift-evolution 
>  wrote:
> 
>> 
>> On Feb 18, 2017, at 10:49 PM, Dave Abrahams via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> I'm on vacation and don't have time for a full review right now, but I am 
>> concerned that wild this proposal would make enums more general and uniform 
>> with the rest of the language , they also would become much more awkward for 
>> common use cases. I have recently been very pleased that I didn't have to 
>> supply labels in switch statements where the label name would simply have 
>> matched the name of the variable to be bound.  This looks needlessly verbose:
>> 
>>   case .valid(value: let value, resumptionPoint: let resumptionPoint):
>> 
>> I cannot imagine a real life use case where one would have labels in the 
>> case and desire to bind associated values to variables having different 
>> names than the labels.
> 
> I agree with this, but I think it’s an issue we can solve (perhaps as an 
> amendment to this proposal).
> 
> First, I think Brent’s idea of introducing an argument label that can be 
> distinct from the “property” name of the case is a good one.  I think we 
> should do this.  It takes the parallel with function signatures even further.
> 
> Second, we should allow the “property” name to be `_`.  This would mean no 
> label can be used when matching:
> 
> case valid(value _: ValueType, resumptionPoint _: PointType)
> 
> Third, I think we should also allow suers to elide the label if they either 
> discard the value with `_` or bind a name that is identical to the label, so 
> we might have:
> 
> // declaration:
> case valid(externalCasConstructorLabel value: ValueType, 
> externalCaseConstructorLabel resumptionPoint: PointType)
> 
> // match ok:
> case .valid(let value, let resumptionPoint):
> 
> // error, names do not match:
> case .valid(let foo, let bar):
> 
> // ok, label is used:
> case .valid(value: let foo, resumptionPoint: let bar):
> 
> This follows the behavior of function signatures very closely.  The external 
> label is used to provide context for the argument at the call site (of the 
> case constructor).  The internal name is used to bind a name to the value 
> that is used by code that works with the value.  
> 
> The only exception here is that because the usage site is distant from the 
> case declaration it may wish to use a different name.  We allow that, but 
> only if the “internal name” is also used in the pattern.  This preserves the 
> ability of a reader of the code to see the name / meaning of the associated 
> value as it was declared by the enum in addition to the name that might make 
> more sense for use in the local context.
> 
>> 
>> Secondly, I can't imagine a case where one would want to use the same case 
>> basename and different labels. The very common use case where the types of 
>> associated values completely distinguish the case and one would rather not 
>> have to supply a case name at all is completely unaddressed. If my quick 
>> read is not mistaken, this proposal makes it legal for cases to have 
>> different complete names (including base name and labels), but doesn't make 
>> it legal to have the same full name (which I would love to be "_" or missing 
>> in some cases) with different associated value types. If we were truly 
>> following the precedent set by function signatures, wouldn't that be 
>> possible too?
> 
> +1.  I think this makes a lot of sense.  It completes the parallel of cases 
> with overloaded functions.
> 
> I think anonymous cases are a really good idea.  I discuss those quite a bit 
> in the value subtyping manifesto I shared last week (I’d love to hear your 
> thoughts on it if / when you have time to take a look).
> 
> How would you propose that values of anonymous cases be constructed and 
> matched?  My solution is to allow them to be constructed by implicit 
> conversion from the associated value type to the enum type and matched by a 
> cast pattern.  Is that what you have in mind?  I would *really* love to see 
> this someday...

I can’t speak for Dave obviously. But I think he was merely proposing 
“overloaded” form of enum options, in which multiple options may share the 
compound name but with differently associated types. The name “_” would just be 
a normal identifier in such scenario. So it would also be the contractor’s 
function name.

>> 
>> Sent from my moss-covered three-handled family gradunza
>> 
>> On Feb 17, 2017, at 5:26 PM, John McCall > > wrote:
>> 
>>> Hello Swift community,
>>> 
>>> The review of "SE-0155: Normalize Enum Case Representation" begins now and 
>>> runs through next Friday, February 26th. The proposal is available here:
>>> 
>>> https://github.com/apple/swift-evolution/blob/master/proposals/0155-normalize-enum-case-representation.md
>>>  
>>> 

Re: [swift-evolution] [Draft] @selfsafe: a new way to avoid reference cycles

2017-02-19 Thread Brent Royal-Gordon via swift-evolution
> On Feb 19, 2017, at 6:45 AM, Matthew Johnson  wrote:
> 
> 1. Swift *already* acknowledges that it is far easier to create a reference 
> cycle through captured strong references to `self` than any other way.  This 
> is why you have to explicitly say `self.` in escaping closures.

The reason you have to explicitly say `self` is that `self` is the only 
variable you can implicitly reference. That's disabled in closures, so it's on 
the same footing as other variables.

Other than that, the only reason `self` is more likely to cause a loop is that, 
in common Cocoa patterns, you're more likely to be handing the closure to 
something owned by `self`. But that's not *necessarily* the case, it just 
happens to be true in many cases.

> 2. There are *already* APIs which are designed to capture an object weak and 
> then call a method on it if it's still around when an event occurs.  In fact 
> this has been a trend in Apple's newer APIs.  Users are able to learn the 
> semantics of these APIs without a problem.  In fact, users like the, because 
> they solve a real problem by ensuring that3.  object lifetime is not extended 
> when using them.
> 
> 3. Swift libraries don't tend to design APIs with weak callback semantics, 
> probably because they are currently syntactically heavy for both users and 
> libraries.  This is true even when weak callback semantics would be 
> beneficial for users and help prevent leaks (which can lead to crashes and 
> other badly behaved apps).
> 
> 4. There have been several ideas proposed to make weak capture easier to do 
> on the call side but they haven't gone anywhere.  The syntactic savings 
> aren't that significant for callers and the burden is still on callers to get 
> it right.

I definitely agree this is a problem, but again, that doesn't mean `self` is 
the issue here. I think this is mainly because (a) the pattern isn't taught, 
and (b) there are some minor speed bumps in current Swift (like the inability 
to shadow `self` in a closure parameter list).

> If users actually need a strong reference there are ways to handle that.  
> First, if it is likely that a user might want self to be captured strong the 
> API might choose to not use `@selfsafe`.

This doesn't work. The API designer doesn't know what's at the call site, and 
the user can't modify the API to suit the use.

> If they *do* choose to use it the could also add an overload that does not 
> use it and is disambiguated using some other means (base name or argument 
> label).

That seems like an ugly way to design APIs.

> Finally, users can always add an extra closure wrapper {{ self.myMethod() }} 
> to bypass the API's weak callback semantics.  Here, `self` is captured by the 
> inner closure rather than the the outer closure and the API only converts 
> strong `self` references in the outer closure.

That wouldn't work. The outer closure captures `self` from the context, and the 
inner closure captures `self` from the outer closure. The outer closure's 
capture would still be weak.

I really think this focus on `self` is counterproductive. I'm thinking we might 
be able to address this in a different way.

Let's look at your code sample:

addAction(takesInt)

With the implicit `self`s made explicit, that would instead be:

self.addAction(
self.takesInt
)

Now let's look at mine:

alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ 
in
…
viewController.performSegue(withIdentifier: "Cancel", sender: 
self)
})
…

viewController.present(alert)

These have a similar pattern: The closure ends up being passed to a method on 
one of the variables it captures. Your example:

self.addAction(
^ Closure gets passed to method on `self`
self.takesInt
^ Closure captures `self`
)

Mine:

alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ 
in
^ Closure passed to method on `alert`
…
viewController.performSegue(withIdentifier: "Cancel", sender: 
self)
^ Closure captures `viewController`
})
…

viewController.present(alert)
^ `alert` passed to `viewController`

This seems like something the compiler—or perhaps a static analyzer?—could warn 
about. And it wouldn't target `self` specifically, or silently change the 
meaning of your code.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
The reason you should not conform to _ExpressibleByBuiltinIntegerLiteral is
that your type does not conform to the semantics of that protocol.

Every protocol guarantees both syntax and semantics. (Well, almost every
protocol; Error has no syntactic requirements at all, only semantic ones.)
However, the compiler (in general) checks only syntax. For instance, it can
ensure that your Equatable type implements ==, but it cannot check whether
that function actually adheres to the three semantic requirements for
equality.

So, in that light, you can offer an infinite list of examples where you
conform a type to a protocol that others might judge questionable. You
might implement == to check for inequality, and then conform that type to
Equatable. You might name a type Success and conform it to Error. It's a
non-goal for the compiler to stop you. I would imagine (although the core
team should correct me if I'm wrong) that a similar line of reasoning is
why the standard library authors are not extremely bothered that you are
not restrained by the compiler from conforming to
_ExpressibleByBuiltinIntegerLiteral.

It'd be quite the sledgehammer to bring down source-breaking syntax changes
in order to help the compiler enforce one particular semantic requirement,
no?

As to enums, I'm sure you're aware that it's a straw man argument you're
bringing up.
On Sun, Feb 19, 2017 at 18:02 Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> struct A : _ExpressibleByBuiltinIntegerLiteral {
> init() {}
> init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) {}
> }
>
> struct B : ExpressibleByIntegerLiteral {
> init(integerLiteral value: A) {}
> }
>
> B(integerLiteral: A())
>
> Here is another example. Am I supposed to do that? Definitely not. Your
> lovely question: *Why not?* Because the protocol starts with an
> underscore. So? Doesn’t prevent me from abusing all semi-hidden protocols.
>
> Where is the enum now to stop me from doing this?
>
> Enums are so heavily abused in Swift, just because they have a special
> ability not being extensible with a constructor.
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Dictionary Enhancements

2017-02-19 Thread Ben Cohen via swift-evolution

> On Feb 19, 2017, at 11:22 AM, Ole Begemann  wrote:
> 
> 
>> On 17 Feb 2017, at 01:26, Ben Cohen via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> Here is a list of commonly requested changes/enhancements to Dictionary, all 
>> of which would probably be appropriate to put together into a single 
>> evolution proposal:
>> 
>> init from/merge in a Sequence of Key/Value pairs (already raised as SE-100: 
>> https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md
>>  
>> ).
>> make the Values view collection a MutableCollection (as in this PR: 
>> https://github.com/apple/swift-evolution/pull/555 
>> ).
>> Add a defaulting subscript get (e.g. counts[key, default: 0] += 1 or 
>> grouped(key, default:[]].append(value)).
>> Add a group by-like init to create a Dictionary from a sequence of V 
>> and a closure (V)->K.
> Out of interest, how would you implement this? Does it require a generics 
> feature that's slated for Swift 4? I tried two approaches that don't compile 
> in a current Swift 3.1 snapshot (and I'm getting a segfault with both 
> examples in a dev snapshot from 2017-02-14):
> 
> 1)
> 
> extension Dictionary {
> // error: same-type constraint 'Value' == '[S.Iterator.Element]' is 
> recursive
> init(values: S, groupedBy: (S.Iterator.Element) -> Key)
> where Value == [S.Iterator.Element] {
> ...
> }
> }
> }
> 
> 2)
> 
> // error: reference to generic type 'Array' requires arguments in <...>
> extension Dictionary where Value == Array {
> init(values: S, groupedBy: (S.Iterator.Element) -> Key)
> where S.Iterator.Element == Value.Element {
> ...
> }
> }
> }
> 


Oops, looks like a bug in the same-type constraint implementation. Ought to 
work in 3.1. Minimal crasher repro:

extension Array {
  func f() 
  where Element == S.Iterator.Element? {

  } 
}

I’ve raised https://bugs.swift.org/browse/SR-4008

It ought to be done with the first one. For the second, you can’t constrain 
Value == Array because Array isn’t a type, needs to be Array.

As an (impractical) workaround, this compiles:

extension Dictionary {
subscript(k: Key, default default: Value) -> Value {
get { return self[k] ?? `default` }
set { self[k] = newValue }
}
}

extension Dictionary where Value: RangeReplaceableCollection {
init(grouping values: S, by: (S.Iterator.Element) -> Key)
where S.Iterator.Element == Value.Iterator.Element {
self = [:]
for x in values {
let k = by(x)
self[k, default: Value()].append(x)
}
}
}


let s = [10,20,22,30,31]
// have to explicitly type the Dictionary as a specific RRC
let d: [Int:[Int]] = Dictionary(grouping: s) { $0%10 }

print(d)


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


Re: [swift-evolution] final + lazy + fileprivate modifiers

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Feb 19, 2017, at 5:52 PM, Tony Arnold via swift-evolution 
>  wrote:
> 
> 
>> On 20 Feb 2017, at 06:25, Jose Cheyo Jimenez via swift-evolution 
>>  wrote:
>> 
>> We need more examples to make this case. 
> 
> How do we provide those examples? This thread has been actively discussed for 
> close to a week now, so it would be good to do something concrete about it. I 
> think Chris’ second suggestion fits my idea of a reasonable “Default” level 
> of privacy when starting out, and fits the model of progressive disclosure as 
> you so excellently pointed out.
> 
> Is this something that should go through a proper Proposal? Is someone doing 
> this already? I’d like to help/contribute if it is.

I will write a proposal to address this problem.

> 
> thanks,
> 
> 
> Tony
> 
> 
> 
> --
> Tony Arnold
> +61 411 268 532
> http://thecocoabots.com/
> 
> ABN: 14831833541
> 
> ___
> 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] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
struct A : _ExpressibleByBuiltinIntegerLiteral {
init() {}
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) {}
}

struct B : ExpressibleByIntegerLiteral {
init(integerLiteral value: A) {}
}

B(integerLiteral: A())
Here is another example. Am I supposed to do that? Definitely not. Your lovely 
question: Why not? Because the protocol starts with an underscore. So? Doesn’t 
prevent me from abusing all semi-hidden protocols.

Where is the enum now to stop me from doing this?

Enums are so heavily abused in Swift, just because they have a special ability 
not being extensible with a constructor.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 5:55 PM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> I don’t see it, can you elaborate a whole proposal first, otherwise I’m
> not convinced. Why?
>

I'm sorry. I'm not sure what you mean. Can you clarify what you'd like to
be more convinced of?


> Am 20. Februar 2017 um 00:51:18, Xiaodi Wu (xiaodi...@gmail.com) schrieb:
>
> On Sun, Feb 19, 2017 at 5:26 PM, Adrian Zubarev <
> adrian.zuba...@devandartist.com> wrote:
>
>> Indeed, I have run into the same issue with this and have a proposal idea
>> saved up regarding anonymous enum cases and subtyping relationships. It
>> would not have been in-scope for phase 1, so I did not write to the list
>> about it. I’m short on time these days, but eventually I’ll propose it
>> unless someone else gets to it first. However, this problem does not
>> justify open vs. public.
>>
>> Why is an anonymous enum case justifying the problem over a closed
>> protocol?
>>
> It's justified because enums are (according to the Swift core team)
> Swift's sum type. That is, when you want something to be "either X or Y"
> (or "one of X, Y, Z, or A"), enums are intended to provide all the
> facilities necessary to express that concisely and with the greatest ease.
> As you recall from discussion about union types, the core team has said
> that in circumstances where that goal is not met (clearly, here), they
> welcome proposals to improve enums so that they serve that use case. That
> is why anonymous enum cases (or some other design to improve the experience
> of using enums as a type for "either X or Y") is justified.
>
> Can an anonymous enum case solve every problem a closed protocol can?
>>
> Perhaps, perhaps not. The point is that you proposed a use case
> purportedly to motivate closed protocols, and I am saying that it is
> insufficient to justify closed protocols because the core team has already
> stated that enums are intended to enable that use case. So it is up to you,
> if you wish to promote this idea, to come up with one or more compelling
> use cases and not for me or others to enumerate every use case for them.
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
I don’t see it, can you elaborate a whole proposal first, otherwise I’m not 
convinced. Why?

-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:51:18, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

On Sun, Feb 19, 2017 at 5:26 PM, Adrian Zubarev 
 wrote:
Indeed, I have run into the same issue with this and have a proposal idea saved 
up regarding anonymous enum cases and subtyping relationships. It would not 
have been in-scope for phase 1, so I did not write to the list about it. I’m 
short on time these days, but eventually I’ll propose it unless someone else 
gets to it first. However, this problem does not justify open vs. public.

Why is an anonymous enum case justifying the problem over a closed protocol?

It's justified because enums are (according to the Swift core team) Swift's sum 
type. That is, when you want something to be "either X or Y" (or "one of X, Y, 
Z, or A"), enums are intended to provide all the facilities necessary to 
express that concisely and with the greatest ease. As you recall from 
discussion about union types, the core team has said that in circumstances 
where that goal is not met (clearly, here), they welcome proposals to improve 
enums so that they serve that use case. That is why anonymous enum cases (or 
some other design to improve the experience of using enums as a type for 
"either X or Y") is justified.

Can an anonymous enum case solve every problem a closed protocol can?

Perhaps, perhaps not. The point is that you proposed a use case purportedly to 
motivate closed protocols, and I am saying that it is insufficient to justify 
closed protocols because the core team has already stated that enums are 
intended to enable that use case. So it is up to you, if you wish to promote 
this idea, to come up with one or more compelling use cases and not for me or 
others to enumerate every use case for them.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Allow use associated type outside of its protocol

2017-02-19 Thread 曹剑楠 via swift-evolution
Thanks! Waiting for the new version.

> 在 2017年2月20日,上午7:42,Xiaodi Wu  写道:
> 
> That is a new feature in Swift 3.1.
> 
> 
> On Sun, Feb 19, 2017 at 5:32 PM, 曹剑楠  > wrote:
> Sorry about my typo:
> 
> public struct Album {
> public let sectionedMediaItemInfos: [Sectioned]?}
> 
> 
> public struct Sectioned : SectionProtocol {
> public let title: String?
> public let items: [Item]
> 
> public init() {
> items = []
> title = nil
> }
> }
> 
> public extension Array where Element == Sectioned {
> 
> var itemsCount: Int {
> return reduce(0) { (result, section) in result + section.items.count }
> }
> 
> var items: [Element.Item] {
> return self.flatMap { $0.items }
> }
> }
> 
> Allow extension Array with strict its Element with a struct type (may be 
> generic) is highly wanted feature.
> 
>> 在 2017年2月20日,上午7:28,曹剑楠 mailto:frog...@163.com>> 写道:
>> 
>> 
>> OK, my fault. That solved the problem.
>> 
>>> var items: [Element.SectionItemType]
>> 
>> I should use this.
>> 
>> How about to allow using generic type Section directly instead of declare a 
>> protocol
>> 
>> ```Swift
>> public extension Array where Element == Section {
>> 
>> var itemsCount: Int {
>> return reduce(0) { (result, section) in result + section.items.count 
>> }
>> }
>> 
>> var items: [Element.SectionItemType] {
>> return self.flatMap { $0.items }
>> }
>> }
>> ```
>> 
>>> 在 2017年2月20日,上午7:14,Xiaodi Wu >> > 写道:
>>> 
>>> On Sun, Feb 19, 2017 at 5:04 PM, 曹剑楠 via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> Hi All,
>>> 
>>> I’m coding for section like data structure. 
>>> For example:
>>> 
>>> I have an Album struct, which has many MediaItems.
>>> It has a sectioned property called "sectionedMediaItemInfos", which is an 
>>> array of sections.
>>> Each section represents for a disc, and has an "items" array contains all 
>>> MedaItems in that disc.
>>> 
>>> The define code is like:
>>> 
>>> ```Swift
>>> public struct Album {
>>> public let sectionedMediaItemInfos: [Sectioned]?
>>> }
>>> 
>>> public struct Sectioned : SectionProtocol {
>>> public let title: String?
>>> public let items: [Item]
>>> 
>>> public init() {
>>> items = []
>>> title = nil
>>> }
>>> }
>>> 
>>> public protocol SectionProtocol {
>>> associatedtype SectionItemType
>>> var items: [SectionItemType] { get }
>>> }
>>> ```
>>> 
>>> Now I want to define some extra properties for sections array, like
>>> "sectionMediaItemInfos"."itemsCount" that count all items in each sections.
>>> So I can write that extension:
>>> 
>>> ```Swift
>>> public extension Array where Element : SectionProtocol {
>>> 
>>> var itemsCount: Int {
>>> return reduce(0) { (result, section) in result + 
>>> section.items.count }
>>> }
>>> 
>>> }
>>> ```
>>> 
>>> So I can get my itemsCount with code like:
>>> 
>>> ```Swift
>>> album.sectionedMediaItemInfos.itemsCount
>>> ```
>>> 
>>> That looks good.
>>> 
>>> Then I want to define code to return all items in this sectioned property.
>>> 
>>> 
>>> ```Swift
>>> public extension Array where Element : SectionProtocol {
>>> var items: [SectionProtocol.SectionItemType] {
>>> return .flatMap { $0.items }
>>> }
>>> }
>>> ```
>>>  
>>> Sorry, I'm reading this quickly, but I'm confused as to why you're not 
>>> writing `var items: [Element.SectionItemType]`. That seems to be what you 
>>> want, no? `SectionProtocol.SectionItemType` has no constraints and, even if 
>>> the grammar allowed you to write it, would have to be equivalent to `Any`.
>>> 
>>> This doesn’t work. It reported as "Cannot use associated type 
>>> 'SectionItemType' outside of its protocol"
>>> 
>>> The only way to achieve my goals is to untyped the extended "items" 
>>> property:
>>> 
>>> ```Swift
>>> public extension Array where Element : SectionProtocol {
>>> var items: [Any] {
>>> return self.flatMap { $0.items }
>>> }
>>> }
>>> ```
>>> 
>>> Which is not perfect for this case.
>>> 
>>> 
>>> So in this special case, I think allow use associated type outside of its 
>>> protocol is necessary.
>>> 
>>> And we may allow define protocol with generic type. That would be more 
>>> convenient.
>>> 
>>> 
>>> ```Swift
>>> public struct Album {
>>> public let sectionedMediaItemInfos: [Sectioned]?
>>> }
>>> 
>>> 
>>> public struct Sectioned : SectionProtocol {
>>> public let title: String?
>>> public let items: [Item]
>>> 
>>> public init() {
>>> items = []
>>> title = nil
>>> }
>>> }
>>> 
>>> public protocol SectionProtocol {
>>> var items: [SectionItemType] { get }
>>> }
>>> 
>>> 
>>> public extension Array where Element : SectionProtocol {
>>> var items: [Element.SectionItemType] {
>>> return self.flatMap { $0.items }
>>> }
>>> }
>>> 
>>> ```
>>> 
>>> Thank all!
>>> 

Re: [swift-evolution] final + lazy + fileprivate modifiers

2017-02-19 Thread Tony Arnold via swift-evolution

> On 20 Feb 2017, at 06:25, Jose Cheyo Jimenez via swift-evolution 
>  wrote:
> 
> We need more examples to make this case. 

How do we provide those examples? This thread has been actively discussed for 
close to a week now, so it would be good to do something concrete about it. I 
think Chris’ second suggestion fits my idea of a reasonable “Default” level of 
privacy when starting out, and fits the model of progressive disclosure as you 
so excellently pointed out.

Is this something that should go through a proper Proposal? Is someone doing 
this already? I’d like to help/contribute if it is.

thanks,


Tony



--
Tony Arnold
+61 411 268 532
http://thecocoabots.com/

ABN: 14831833541

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 5:26 PM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> Indeed, I have run into the same issue with this and have a proposal idea
> saved up regarding anonymous enum cases and subtyping relationships. It
> would not have been in-scope for phase 1, so I did not write to the list
> about it. I’m short on time these days, but eventually I’ll propose it
> unless someone else gets to it first. However, this problem does not
> justify open vs. public.
>
> Why is an anonymous enum case justifying the problem over a closed
> protocol?
>
It's justified because enums are (according to the Swift core team) Swift's
sum type. That is, when you want something to be "either X or Y" (or "one
of X, Y, Z, or A"), enums are intended to provide all the facilities
necessary to express that concisely and with the greatest ease. As you
recall from discussion about union types, the core team has said that in
circumstances where that goal is not met (clearly, here), they welcome
proposals to improve enums so that they serve that use case. That is why
anonymous enum cases (or some other design to improve the experience of
using enums as a type for "either X or Y") is justified.

Can an anonymous enum case solve every problem a closed protocol can?
>
> Perhaps, perhaps not. The point is that you proposed a use case
purportedly to motivate closed protocols, and I am saying that it is
insufficient to justify closed protocols because the core team has already
stated that enums are intended to enable that use case. So it is up to you,
if you wish to promote this idea, to come up with one or more compelling
use cases and not for me or others to enumerate every use case for them.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Allow use associated type outside of its protocol

2017-02-19 Thread Xiaodi Wu via swift-evolution
That is a new feature in Swift 3.1.


On Sun, Feb 19, 2017 at 5:32 PM, 曹剑楠  wrote:

> Sorry about my typo:
>
> public struct Album {
>> public let sectionedMediaItemInfos: [Sectioned]?}
>>
>>
>> public struct Sectioned : SectionProtocol {
>> public let title: String?
>> public let items: [Item]
>>
>> public init() {
>> items = []
>> title = nil
>> }
>> }
>>
>
> public extension Array where Element == Sectioned {
>
>
> var itemsCount: Int {
> return reduce(0) { (result, section) in result +
> section.items.count }
> }
>
>
> var items: [Element.Item] {
> return self.flatMap { $0.items }
> }
> }
>
> Allow extension Array with strict its Element with a struct type (may be
> generic) is highly wanted feature.
>
> 在 2017年2月20日,上午7:28,曹剑楠  写道:
>
>
> OK, my fault. That solved the problem.
>
> var items: [Element.SectionItemType]
>>
>
> I should use this.
>
> How about to allow using generic type Section directly instead of declare
> a protocol
>
> ```Swift
> public extension Array where Element == Section {
>
> var itemsCount: Int {
> return reduce(0) { (result, section) in result +
> section.items.count }
> }
>
> var items: [Element.SectionItemType] {
> return self.flatMap { $0.items }
> }
> }
> ```
>
> 在 2017年2月20日,上午7:14,Xiaodi Wu  写道:
>
> On Sun, Feb 19, 2017 at 5:04 PM, 曹剑楠 via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> Hi All,
>>
>> I’m coding for section like data structure.
>> For example:
>>
>> I have an Album struct, which has many MediaItems.
>> It has a sectioned property called "sectionedMediaItemInfos", which is an
>> array of sections.
>> Each section represents for a disc, and has an "items" array contains
>> all MedaItems in that disc.
>>
>> The define code is like:
>>
>> ```Swift
>> public struct Album {
>> public let sectionedMediaItemInfos: [Sectioned]?
>> }
>>
>> public struct Sectioned : SectionProtocol {
>> public let title: String?
>> public let items: [Item]
>>
>> public init() {
>> items = []
>> title = nil
>> }
>> }
>>
>> public protocol SectionProtocol {
>> associatedtype SectionItemType
>> var items: [SectionItemType] { get }
>> }
>> ```
>>
>> Now I want to define some extra properties for sections array, like
>> "sectionMediaItemInfos"."itemsCount" that count all items in each
>> sections.
>> So I can write that extension:
>>
>> ```Swift
>> public extension Array where Element : SectionProtocol {
>>
>> var itemsCount: Int {
>> return reduce(0) { (result, section) in result + section.items.
>> count }
>> }
>>
>> }
>> ```
>>
>> So I can get my itemsCount with code like:
>>
>> ```Swift
>> album.sectionedMediaItemInfos.itemsCount
>> ```
>>
>> That looks good.
>>
>> Then I want to define code to return all items in this sectioned property.
>>
>>
>> ```Swift
>> public extension Array where Element : SectionProtocol {
>> var items: [SectionProtocol.SectionItemType] {
>> return .flatMap { $0.items }
>> }
>> }
>> ```
>>
>
> Sorry, I'm reading this quickly, but I'm confused as to why you're not
> writing `var items: [Element.SectionItemType]`. That seems to be what you
> want, no? `SectionProtocol.SectionItemType` has no constraints and, even
> if the grammar allowed you to write it, would have to be equivalent to
> `Any`.
>
> This doesn’t work. It reported as "Cannot use associated type
>> 'SectionItemType' outside of its protocol"
>>
>> The only way to achieve my goals is to untyped the extended "items"
>> property:
>>
>> ```Swift
>> public extension Array where Element : SectionProtocol {
>> var items: [Any] {
>> return self.flatMap { $0.items }
>> }
>> }
>> ```
>>
>> Which is not perfect for this case.
>>
>>
>> So in this special case, I think allow use associated type outside of its
>> protocol is necessary.
>>
>> And we may allow define protocol with generic type. That would be more
>> convenient.
>>
>>
>> ```Swift
>> public struct Album {
>> public let sectionedMediaItemInfos: [Sectioned]?
>> }
>>
>>
>> public struct Sectioned : SectionProtocol {
>> public let title: String?
>> public let items: [Item]
>>
>> public init() {
>> items = []
>> title = nil
>> }
>> }
>>
>> public protocol SectionProtocol {
>> var items: [SectionItemType] { get }
>> }
>>
>>
>> public extension Array where Element : SectionProtocol {
>> var items: [Element.SectionItemType] {
>> return self.flatMap { $0.items }
>> }
>> }
>>
>> ```
>>
>> Thank all!
>>
>> Jiannan
>>
>>
>>
>>
>> ___
>> 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] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 5:15 PM, Brent Royal-Gordon via swift-evolution <
swift-evolution@swift.org> wrote:

> > On Feb 18, 2017, at 10:58 PM, David Waite via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > I am unsure if this feature is a good idea. Does someone have a
> real-world use for this which isn’t just hiding strong implementation
> coupling behind a protocol?
>
> Strong coupling is sometimes inevitable.
>
> In a previous thread, I brought up an example of a place I would use this
> feature: Wrapping the SQLite APIs. For instance:
>
> public protocol SQLiteValue {
> init(statement: SQLiteStatement, columnAt index: Int)
> throws
> func bind(to statement: SQLiteStatement, at index: Int)
> throws
> }
> extension Int: SQLiteValue {
> public init(statement: SQLiteStatement, columnAt index:
> Int) throws {
> self = sqlite3_column_int(statement.stmt, index)
> }
> public func bind(to statement: SQLiteStatement, at index:
> Int) throws {
> try throwIfNotOK(
> sqlite3_bind_int64(statement.stmt, index,
> self)
> )
> }
> }
> extension Double: SQLiteValue {…}
> extension Data: SQLiteValue {…}
> extension String: SQLiteValue {…}
> extension Optional: SQLiteValue where Wrapped: SQLiteValue {…}
>
> This is a case of your hated "strong implementation coupling". But the
> coupling is to a library that ultimately writes data to disk in a portable
> format. Strong coupling here is inevitable.
>
> What is the purpose of permitting outside conformances to `SQLiteValue`?


Suppose you released this library and I used it for my SQLite needs. But my
application uses Float behind the scenes, which can be losslessly promoted
(as you must know) as Double. For convenience of interfacing with your
library, I conform Float to SQLiteValue. Likewise, let's say I implement a
new Rational type (not actually hypothetical, hehe), and I decide that I
want to store that as Double (it'd be precise enough once all the
calculations are done). For convenience, I conform Rational to
SQLiteValue. I could make good on these conformances by having `init()` and
`bind(to:at:)` do a numeric cast and then forward to the relevant methods
on Double. Now, I understand why your library wouldn't do this, since
willy-nilly conversions between types are worth at least careful thought,
but as a non-library client that uses Float pervasively, I'd have good
justification for that extension.

There is no useful way to conform to `SQLiteValue`; the underlying library
> supports certain types, and I've implemented support for those types.
> Allowing outside conformances can only mislead people into fruitlessly
> trying to conform their types, not realizing that the calls they need
> simply aren't exposed.
>

What is the harm of permitting an outside conformance to `SQLiteValue`?


> Moreover, exposing these details unnecessarily freezes the design of
> `SQLiteValue`. If I want to change the design of this parameter handling in
> a future version, well, too bad, the API is public, I'm stuck. *For an API
> I don't intend anyone to conform to publicly in the first place.* That kind
> of sucks, doesn't it?
>

But with `public` vs `open`, your API is still frozen whichever you choose.
Even if you can't conform to `SQLiteValue`, there is no guarantee that your
clients won't _invoke_ `SQLiteValue.bind(to:at:)`, so you can't redesign
the protocol anyway. What other flexibility are you looking for?


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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread David Hart via swift-evolution
It’s funny. My favourites SQLite library actually does it as I suggested :)

https://github.com/groue/GRDB.swift/blob/master/GRDB/Core/DatabaseValue.swift

> On 20 Feb 2017, at 00:34, David Hart  wrote:
> 
>> 
>> On 20 Feb 2017, at 00:15, Brent Royal-Gordon via swift-evolution 
>>  wrote:
>> 
>>> On Feb 18, 2017, at 10:58 PM, David Waite via swift-evolution 
>>>  wrote:
>>> 
>>> I am unsure if this feature is a good idea. Does someone have a real-world 
>>> use for this which isn’t just hiding strong implementation coupling behind 
>>> a protocol?
>> 
>> Strong coupling is sometimes inevitable.
>> 
>> In a previous thread, I brought up an example of a place I would use this 
>> feature: Wrapping the SQLite APIs. For instance:
>> 
>>  public protocol SQLiteValue {
>>  init(statement: SQLiteStatement, columnAt index: Int) throws
>>  func bind(to statement: SQLiteStatement, at index: Int) throws
>>  }
>>  extension Int: SQLiteValue {
>>  public init(statement: SQLiteStatement, columnAt index: Int) 
>> throws {
>>  self = sqlite3_column_int(statement.stmt, index)
>>  }
>>  public func bind(to statement: SQLiteStatement, at index: Int) 
>> throws {
>>  try throwIfNotOK(
>>  sqlite3_bind_int64(statement.stmt, index, self)
>>  )
>>  }
>>  }
>>  extension Double: SQLiteValue {…}
>>  extension Data: SQLiteValue {…}
>>  extension String: SQLiteValue {…}
>>  extension Optional: SQLiteValue where Wrapped: SQLiteValue {…}
> 
> That problem is that I don’t think the API should be written this way. This 
> cries for the use of enums instead:
> 
> enum SQLiteValue {
>case int(Int)
>case double(Double)
>case data(Data)
>case string(String)
> }
> 
> protocol SQLiteValueConvertible {
>var sqliteValue: SQLiteValue { get }
> }
> 
> extension Int : SQLiteValueConvertible {
>var sqliteValue: SQLiteValue { return .int(self) }
> }
> 
> And that API actually allows interesting extension points. For example, how 
> about automatic binding of dates:
> 
> extension Date : SQLiteValueConvertible {
>var sqliteValue: SQLiteValue { return .double(timeIntervalSince1970) }
> }
> 
> I keep getting the impression that the uses for the proposals are actually 
> cases where an enum is required.
> 
>> This is a case of your hated "strong implementation coupling". But the 
>> coupling is to a library that ultimately writes data to disk in a portable 
>> format. Strong coupling here is inevitable.
>> 
>> What is the purpose of permitting outside conformances to `SQLiteValue`? 
>> There is no useful way to conform to `SQLiteValue`; the underlying library 
>> supports certain types, and I've implemented support for those types. 
>> Allowing outside conformances can only mislead people into fruitlessly 
>> trying to conform their types, not realizing that the calls they need simply 
>> aren't exposed.
>> 
>> Moreover, exposing these details unnecessarily freezes the design of 
>> `SQLiteValue`. If I want to change the design of this parameter handling in 
>> a future version, well, too bad, the API is public, I'm stuck. *For an API I 
>> don't intend anyone to conform to publicly in the first place.* That kind of 
>> sucks, doesn't 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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread David Hart via swift-evolution

> On 20 Feb 2017, at 00:15, Brent Royal-Gordon via swift-evolution 
>  wrote:
> 
>> On Feb 18, 2017, at 10:58 PM, David Waite via swift-evolution 
>>  wrote:
>> 
>> I am unsure if this feature is a good idea. Does someone have a real-world 
>> use for this which isn’t just hiding strong implementation coupling behind a 
>> protocol?
> 
> Strong coupling is sometimes inevitable.
> 
> In a previous thread, I brought up an example of a place I would use this 
> feature: Wrapping the SQLite APIs. For instance:
> 
>   public protocol SQLiteValue {
>   init(statement: SQLiteStatement, columnAt index: Int) throws
>   func bind(to statement: SQLiteStatement, at index: Int) throws
>   }
>   extension Int: SQLiteValue {
>   public init(statement: SQLiteStatement, columnAt index: Int) 
> throws {
>   self = sqlite3_column_int(statement.stmt, index)
>   }
>   public func bind(to statement: SQLiteStatement, at index: Int) 
> throws {
>   try throwIfNotOK(
>   sqlite3_bind_int64(statement.stmt, index, self)
>   )
>   }
>   }
>   extension Double: SQLiteValue {…}
>   extension Data: SQLiteValue {…}
>   extension String: SQLiteValue {…}
>   extension Optional: SQLiteValue where Wrapped: SQLiteValue {…}

That problem is that I don’t think the API should be written this way. This 
cries for the use of enums instead:

enum SQLiteValue {
case int(Int)
case double(Double)
case data(Data)
case string(String)
}

protocol SQLiteValueConvertible {
var sqliteValue: SQLiteValue { get }
}

extension Int : SQLiteValueConvertible {
var sqliteValue: SQLiteValue { return .int(self) }
}

And that API actually allows interesting extension points. For example, how 
about automatic binding of dates:

extension Date : SQLiteValueConvertible {
var sqliteValue: SQLiteValue { return .double(timeIntervalSince1970) }
}

I keep getting the impression that the uses for the proposals are actually 
cases where an enum is required.

> This is a case of your hated "strong implementation coupling". But the 
> coupling is to a library that ultimately writes data to disk in a portable 
> format. Strong coupling here is inevitable.
> 
> What is the purpose of permitting outside conformances to `SQLiteValue`? 
> There is no useful way to conform to `SQLiteValue`; the underlying library 
> supports certain types, and I've implemented support for those types. 
> Allowing outside conformances can only mislead people into fruitlessly trying 
> to conform their types, not realizing that the calls they need simply aren't 
> exposed.
> 
> Moreover, exposing these details unnecessarily freezes the design of 
> `SQLiteValue`. If I want to change the design of this parameter handling in a 
> future version, well, too bad, the API is public, I'm stuck. *For an API I 
> don't intend anyone to conform to publicly in the first place.* That kind of 
> sucks, doesn't 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


Re: [swift-evolution] [Pitch] Allow use associated type outside of its protocol

2017-02-19 Thread 曹剑楠 via swift-evolution
Sorry about my typo:

public struct Album {
public let sectionedMediaItemInfos: [Sectioned]?}


public struct Sectioned : SectionProtocol {
public let title: String?
public let items: [Item]

public init() {
items = []
title = nil
}
}

public extension Array where Element == Sectioned {

var itemsCount: Int {
return reduce(0) { (result, section) in result + section.items.count }
}

var items: [Element.Item] {
return self.flatMap { $0.items }
}
}

Allow extension Array with strict its Element with a struct type (may be 
generic) is highly wanted feature.

> 在 2017年2月20日,上午7:28,曹剑楠  写道:
> 
> 
> OK, my fault. That solved the problem.
> 
>> var items: [Element.SectionItemType]
> 
> I should use this.
> 
> How about to allow using generic type Section directly instead of declare a 
> protocol
> 
> ```Swift
> public extension Array where Element == Section {
> 
> var itemsCount: Int {
> return reduce(0) { (result, section) in result + section.items.count }
> }
> 
> var items: [Element.SectionItemType] {
> return self.flatMap { $0.items }
> }
> }
> ```
> 
>> 在 2017年2月20日,上午7:14,Xiaodi Wu > > 写道:
>> 
>> On Sun, Feb 19, 2017 at 5:04 PM, 曹剑楠 via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> Hi All,
>> 
>> I’m coding for section like data structure. 
>> For example:
>> 
>> I have an Album struct, which has many MediaItems.
>> It has a sectioned property called "sectionedMediaItemInfos", which is an 
>> array of sections.
>> Each section represents for a disc, and has an "items" array contains all 
>> MedaItems in that disc.
>> 
>> The define code is like:
>> 
>> ```Swift
>> public struct Album {
>> public let sectionedMediaItemInfos: [Sectioned]?
>> }
>> 
>> public struct Sectioned : SectionProtocol {
>> public let title: String?
>> public let items: [Item]
>> 
>> public init() {
>> items = []
>> title = nil
>> }
>> }
>> 
>> public protocol SectionProtocol {
>> associatedtype SectionItemType
>> var items: [SectionItemType] { get }
>> }
>> ```
>> 
>> Now I want to define some extra properties for sections array, like
>> "sectionMediaItemInfos"."itemsCount" that count all items in each sections.
>> So I can write that extension:
>> 
>> ```Swift
>> public extension Array where Element : SectionProtocol {
>> 
>> var itemsCount: Int {
>> return reduce(0) { (result, section) in result + section.items.count 
>> }
>> }
>> 
>> }
>> ```
>> 
>> So I can get my itemsCount with code like:
>> 
>> ```Swift
>> album.sectionedMediaItemInfos.itemsCount
>> ```
>> 
>> That looks good.
>> 
>> Then I want to define code to return all items in this sectioned property.
>> 
>> 
>> ```Swift
>> public extension Array where Element : SectionProtocol {
>> var items: [SectionProtocol.SectionItemType] {
>> return .flatMap { $0.items }
>> }
>> }
>> ```
>>  
>> Sorry, I'm reading this quickly, but I'm confused as to why you're not 
>> writing `var items: [Element.SectionItemType]`. That seems to be what you 
>> want, no? `SectionProtocol.SectionItemType` has no constraints and, even if 
>> the grammar allowed you to write it, would have to be equivalent to `Any`.
>> 
>> This doesn’t work. It reported as "Cannot use associated type 
>> 'SectionItemType' outside of its protocol"
>> 
>> The only way to achieve my goals is to untyped the extended "items" property:
>> 
>> ```Swift
>> public extension Array where Element : SectionProtocol {
>> var items: [Any] {
>> return self.flatMap { $0.items }
>> }
>> }
>> ```
>> 
>> Which is not perfect for this case.
>> 
>> 
>> So in this special case, I think allow use associated type outside of its 
>> protocol is necessary.
>> 
>> And we may allow define protocol with generic type. That would be more 
>> convenient.
>> 
>> 
>> ```Swift
>> public struct Album {
>> public let sectionedMediaItemInfos: [Sectioned]?
>> }
>> 
>> 
>> public struct Sectioned : SectionProtocol {
>> public let title: String?
>> public let items: [Item]
>> 
>> public init() {
>> items = []
>> title = nil
>> }
>> }
>> 
>> public protocol SectionProtocol {
>> var items: [SectionItemType] { get }
>> }
>> 
>> 
>> public extension Array where Element : SectionProtocol {
>> var items: [Element.SectionItemType] {
>> return self.flatMap { $0.items }
>> }
>> }
>> 
>> ```
>> 
>> Thank all!
>> 
>> Jiannan
>> 
>> 
>> 
>> 
>> ___
>> 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/

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
Because it’s not up to the client to decide how the design of the API supposed 
to work.

-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:28:38, David Hart (da...@hartbit.com) schrieb:


On 20 Feb 2017, at 00:19, Adrian Zubarev  
wrote:

I’m polite but I don’t see why every single piece is questioned with “why”.

Your example is exactly the workaround I presented in first place. Interesting 
right? But it still fails the challenge, because the set of types can be 
extended by the client, however at least with this there won’t be any runtime 
crashes in Swift 3.X

In this example, I don’t see why it’s a problem to have types be extended by 
the client:

struct Person {
    let firstName: String
    let lastName: String
    let id: String
}

extension Person : KeyConvertible {
    var key: Key {
        return .string(id)
    }
}

-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:14:28, David Hart (da...@hartbit.com) schrieb:


On 20 Feb 2017, at 00:10, Adrian Zubarev via swift-evolution 
 wrote:

Because someInstance["key", .string("key1"), .integer(1), 
.string(stringKeyInstance), .integer(intIndexInstance), 
.integer(intIndexInstance), …] is simply ugly and should be hidden. Such API 
looks horrible.

Is this discussion really going to end with every statement being questioned 
with “why”? Why is 42 the number that rules the universe?

Lets stay polite and keep things civil.

The "the client should not be able to extend the set of types you can pass to 
that subscript.” requirement seems totally arbitrary and an anti-pattern. I’m 
perfectly happy with:

enum Key {
    case string(String)
    case int(Int)
}

protocol KeyConvertible {
    var key: Key { get }
}

subscript(initial: String, others: KeyConvertible...) -> Foo

-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:03:44, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev 
 wrote:
Matthew has pretty much summed up everything with a single question in his last 
reply. It makes me tired of repeating myself over and over again.

Here’s the challenge for you:

Implement a subscript where the first parameter is a String (trivial), but the 
second to n are String’s and/or Int’s. There is no restriction of order for the 
Int’s and String’s and there could be as many as you’d like, so no overloads 
are allowed (a hint: variadics). You should be able to use variables in that 
subscript and literals. You’re not allowed to use enum constructors

Why not? You want a parameter that takes either String or Int. In another 
language, you might express this as `String | Int`, but Chris Lattner and 
others have said on this list that enums are the intended way of expressing 
this in Swift.
and the client should not be able to extend the set of types you can pass to 
that subscript. That said it can look like this: someInstance["key", "key1", 1, 
stringKeyInstance, intIndexInstance, intIndexInstance, …]

Creating hacks like unreachable types with hidden inits is prohibited.

Have fun!



-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

Sorry, I have read through this thread twice and do not understand the point 
you are making. Can you explain your example once more?

Specifically, I do not understand why it is that your code should have problems 
with third-party types that conform to your protocol. If your protocol has 
requirements that third-party types cannot fulfill, then naturally those 
requirements will prevent a third-party from conforming new types to your 
protocol. OTOH, if your protocol does not have any requirements that 
third-party types cannot fulfill, then your code that accepts anything that 
conforms to your protocol should be indifferent to whether the conforming type 
is defined by you or someone else. After all, a conforming type would fulfill 
all the semantic and syntactic requirements of the protocol! If your protocol 
has requirements that you are unable to state in code, causing third-party 
types to conform that really shouldn't, then that is a case for additional 
features that allow you to express those requirements more accurately, not an 
argument for having protocols that can't be conformed to by a third-party. What 
am I missing?


On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
 wrote:
That’s the whole point I was making. :) Thank you Matthew. That makes my 
example a real world example and not just some bike shedding.

-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com) 
schrieb:



Sent from my iPad

On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
 wrote:

Just FYI, I solved this issue in my own library (which included a json jpointer 
implementation) via:

public enum SubscriptParameter {
  case string(String)
  case int(Int)
}

extension SubscriptParameter : ExpressibleByIntegerLiteral {

Re: [swift-evolution] [Pitch] Allow use associated type outside of its protocol

2017-02-19 Thread 曹剑楠 via swift-evolution

OK, my fault. That solved the problem.

> var items: [Element.SectionItemType]

I should use this.

How about to allow using generic type Section directly instead of declare a 
protocol

```Swift
public extension Array where Element == Section {

var itemsCount: Int {
return reduce(0) { (result, section) in result + section.items.count }
}

var items: [Element.SectionItemType] {
return self.flatMap { $0.items }
}
}
```

> 在 2017年2月20日,上午7:14,Xiaodi Wu  写道:
> 
> On Sun, Feb 19, 2017 at 5:04 PM, 曹剑楠 via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> Hi All,
> 
> I’m coding for section like data structure. 
> For example:
> 
> I have an Album struct, which has many MediaItems.
> It has a sectioned property called "sectionedMediaItemInfos", which is an 
> array of sections.
> Each section represents for a disc, and has an "items" array contains all 
> MedaItems in that disc.
> 
> The define code is like:
> 
> ```Swift
> public struct Album {
> public let sectionedMediaItemInfos: [Sectioned]?
> }
> 
> public struct Sectioned : SectionProtocol {
> public let title: String?
> public let items: [Item]
> 
> public init() {
> items = []
> title = nil
> }
> }
> 
> public protocol SectionProtocol {
> associatedtype SectionItemType
> var items: [SectionItemType] { get }
> }
> ```
> 
> Now I want to define some extra properties for sections array, like
> "sectionMediaItemInfos"."itemsCount" that count all items in each sections.
> So I can write that extension:
> 
> ```Swift
> public extension Array where Element : SectionProtocol {
> 
> var itemsCount: Int {
> return reduce(0) { (result, section) in result + section.items.count }
> }
> 
> }
> ```
> 
> So I can get my itemsCount with code like:
> 
> ```Swift
> album.sectionedMediaItemInfos.itemsCount
> ```
> 
> That looks good.
> 
> Then I want to define code to return all items in this sectioned property.
> 
> 
> ```Swift
> public extension Array where Element : SectionProtocol {
> var items: [SectionProtocol.SectionItemType] {
> return .flatMap { $0.items }
> }
> }
> ```
>  
> Sorry, I'm reading this quickly, but I'm confused as to why you're not 
> writing `var items: [Element.SectionItemType]`. That seems to be what you 
> want, no? `SectionProtocol.SectionItemType` has no constraints and, even if 
> the grammar allowed you to write it, would have to be equivalent to `Any`.
> 
> This doesn’t work. It reported as "Cannot use associated type 
> 'SectionItemType' outside of its protocol"
> 
> The only way to achieve my goals is to untyped the extended "items" property:
> 
> ```Swift
> public extension Array where Element : SectionProtocol {
> var items: [Any] {
> return self.flatMap { $0.items }
> }
> }
> ```
> 
> Which is not perfect for this case.
> 
> 
> So in this special case, I think allow use associated type outside of its 
> protocol is necessary.
> 
> And we may allow define protocol with generic type. That would be more 
> convenient.
> 
> 
> ```Swift
> public struct Album {
> public let sectionedMediaItemInfos: [Sectioned]?
> }
> 
> 
> public struct Sectioned : SectionProtocol {
> public let title: String?
> public let items: [Item]
> 
> public init() {
> items = []
> title = nil
> }
> }
> 
> public protocol SectionProtocol {
> var items: [SectionItemType] { get }
> }
> 
> 
> public extension Array where Element : SectionProtocol {
> var items: [Element.SectionItemType] {
> return self.flatMap { $0.items }
> }
> }
> 
> ```
> 
> Thank all!
> 
> Jiannan
> 
> 
> 
> 
> ___
> 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] open and public protocols

2017-02-19 Thread David Hart via swift-evolution

> On 20 Feb 2017, at 00:19, Adrian Zubarev  
> wrote:
> 
> I’m polite but I don’t see why every single piece is questioned with “why”.
> 
> Your example is exactly the workaround I presented in first place. 
> Interesting right? But it still fails the challenge, because the set of types 
> can be extended by the client, however at least with this there won’t be any 
> runtime crashes in Swift 3.X
> 
In this example, I don’t see why it’s a problem to have types be extended by 
the client:

struct Person {
let firstName: String
let lastName: String
let id: String
}

extension Person : KeyConvertible {
var key: Key {
return .string(id)
}
}

> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 20. Februar 2017 um 00:14:28, David Hart (da...@hartbit.com 
> ) schrieb:
> 
>> 
>>> On 20 Feb 2017, at 00:10, Adrian Zubarev via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> Because someInstance["key", .string("key1"), .integer(1), 
>>> .string(stringKeyInstance), .integer(intIndexInstance), 
>>> .integer(intIndexInstance), …] is simply ugly and should be hidden. Such 
>>> API looks horrible.
>>> 
>>> Is this discussion really going to end with every statement being 
>>> questioned with “why”? Why is 42 the number that rules the universe?
>>> 
>> Lets stay polite and keep things civil.
>> 
>> The "the client should not be able to extend the set of types you can pass 
>> to that subscript.” requirement seems totally arbitrary and an anti-pattern. 
>> I’m perfectly happy with:
>> 
>> enum Key {
>> case string(String)
>> case int(Int)
>> }
>> 
>> protocol KeyConvertible {
>> var key: Key { get }
>> }
>> 
>> subscript(initial: String, others: KeyConvertible...) -> Foo
>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> Am 20. Februar 2017 um 00:03:44, Xiaodi Wu (xiaodi...@gmail.com 
>>> ) schrieb:
>>> 
 On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev 
 mailto:adrian.zuba...@devandartist.com>> 
 wrote:
 Matthew has pretty much summed up everything with a single question in his 
 last reply. It makes me tired of repeating myself over and over again.
 
 Here’s the challenge for you:
 
 Implement a subscript where the first parameter is a String (trivial), but 
 the second to n are String’s and/or Int’s. There is no restriction of 
 order for the Int’s and String’s and there could be as many as you’d like, 
 so no overloads are allowed (a hint: variadics). You should be able to use 
 variables in that subscript and literals. You’re not allowed to use enum 
 constructors
 
 Why not? You want a parameter that takes either String or Int. In another 
 language, you might express this as `String | Int`, but Chris Lattner and 
 others have said on this list that enums are the intended way of 
 expressing this in Swift.
 and the client should not be able to extend the set of types you can pass 
 to that subscript. That said it can look like this: someInstance["key", 
 "key1", 1, stringKeyInstance, intIndexInstance, intIndexInstance, …]
 
 Creating hacks like unreachable types with hidden inits is prohibited.
 
 Have fun!
 
 
 
 -- 
 Adrian Zubarev
 Sent with Airmail
 
 Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com 
 ) schrieb:
 
> Sorry, I have read through this thread twice and do not understand the 
> point you are making. Can you explain your example once more?
> 
> Specifically, I do not understand why it is that your code should have 
> problems with third-party types that conform to your protocol. If your 
> protocol has requirements that third-party types cannot fulfill, then 
> naturally those requirements will prevent a third-party from conforming 
> new types to your protocol. OTOH, if your protocol does not have any 
> requirements that third-party types cannot fulfill, then your code that 
> accepts anything that conforms to your protocol should be indifferent to 
> whether the conforming type is defined by you or someone else. After all, 
> a conforming type would fulfill all the semantic and syntactic 
> requirements of the protocol! If your protocol has requirements that you 
> are unable to state in code, causing third-party types to conform that 
> really shouldn't, then that is a case for additional features that allow 
> you to express those requirements more accurately, not an argument for 
> having protocols that can't be conformed to by a third-party. What am I 
> missing?
> 
> 
> On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> That’s the whole point I was making. :) Thank you Matthew. That makes my 
> example a real world example and not

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
Indeed, I have run into the same issue with this and have a proposal idea saved 
up regarding anonymous enum cases and subtyping relationships. It would not 
have been in-scope for phase 1, so I did not write to the list about it. I’m 
short on time these days, but eventually I’ll propose it unless someone else 
gets to it first. However, this problem does not justify open vs. public.
Why is an anonymous enum case justifying the problem over a closed protocol? 
Can an anonymous enum case solve every problem a closed protocol can?

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
Indeed, I have run into the same issue with this and have a proposal idea saved 
up regarding anonymous enum cases and subtyping relationships. It would not 
have been in-scope for phase 1, so I did not write to the list about it. I’m 
short on time these days, but eventually I’ll propose it unless someone else 
gets to it first. However, this problem does not justify open vs. public.
Why is an anonymous enum case justifying the problem over a closed protocol?

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
I’m polite but I don’t see why every single piece is questioned with “why”.

Your example is exactly the workaround I presented in first place. Interesting 
right? But it still fails the challenge, because the set of types can be 
extended by the client, however at least with this there won’t be any runtime 
crashes in Swift 3.X.



-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:14:28, David Hart (da...@hartbit.com) schrieb:


On 20 Feb 2017, at 00:10, Adrian Zubarev via swift-evolution 
 wrote:

Because someInstance["key", .string("key1"), .integer(1), 
.string(stringKeyInstance), .integer(intIndexInstance), 
.integer(intIndexInstance), …] is simply ugly and should be hidden. Such API 
looks horrible.

Is this discussion really going to end with every statement being questioned 
with “why”? Why is 42 the number that rules the universe?

Lets stay polite and keep things civil.

The "the client should not be able to extend the set of types you can pass to 
that subscript.” requirement seems totally arbitrary and an anti-pattern. I’m 
perfectly happy with:

enum Key {
    case string(String)
    case int(Int)
}

protocol KeyConvertible {
    var key: Key { get }
}

subscript(initial: String, others: KeyConvertible...) -> Foo

-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:03:44, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev 
 wrote:
Matthew has pretty much summed up everything with a single question in his last 
reply. It makes me tired of repeating myself over and over again.

Here’s the challenge for you:

Implement a subscript where the first parameter is a String (trivial), but the 
second to n are String’s and/or Int’s. There is no restriction of order for the 
Int’s and String’s and there could be as many as you’d like, so no overloads 
are allowed (a hint: variadics). You should be able to use variables in that 
subscript and literals. You’re not allowed to use enum constructors

Why not? You want a parameter that takes either String or Int. In another 
language, you might express this as `String | Int`, but Chris Lattner and 
others have said on this list that enums are the intended way of expressing 
this in Swift.
and the client should not be able to extend the set of types you can pass to 
that subscript. That said it can look like this: someInstance["key", "key1", 1, 
stringKeyInstance, intIndexInstance, intIndexInstance, …]

Creating hacks like unreachable types with hidden inits is prohibited.

Have fun!



-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

Sorry, I have read through this thread twice and do not understand the point 
you are making. Can you explain your example once more?

Specifically, I do not understand why it is that your code should have problems 
with third-party types that conform to your protocol. If your protocol has 
requirements that third-party types cannot fulfill, then naturally those 
requirements will prevent a third-party from conforming new types to your 
protocol. OTOH, if your protocol does not have any requirements that 
third-party types cannot fulfill, then your code that accepts anything that 
conforms to your protocol should be indifferent to whether the conforming type 
is defined by you or someone else. After all, a conforming type would fulfill 
all the semantic and syntactic requirements of the protocol! If your protocol 
has requirements that you are unable to state in code, causing third-party 
types to conform that really shouldn't, then that is a case for additional 
features that allow you to express those requirements more accurately, not an 
argument for having protocols that can't be conformed to by a third-party. What 
am I missing?


On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
 wrote:
That’s the whole point I was making. :) Thank you Matthew. That makes my 
example a real world example and not just some bike shedding.

-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com) 
schrieb:



Sent from my iPad

On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
 wrote:

Just FYI, I solved this issue in my own library (which included a json jpointer 
implementation) via:

public enum SubscriptParameter {
  case string(String)
  case int(Int)
}

extension SubscriptParameter : ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    self = .int(value)
  }
}

extension SubscriptParameter : ExpressibleByStringLiteral {
  public init(stringLiteral value: String) {
    self = .string(value)
  }
  public init(extendedGraphemeClusterLiteral value: String) {
    self.init(stringLiteral: value)
  }
  public init(unicodeScalarLiteral value: String) {
    self.init(stringLiteral: value)
  }
}

extension SubscriptParameter : CustomStringConvertible {
  public var description: String {
    switch self {
    cas

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 5:10 PM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> Because someInstance["key", .string("key1"), .integer(1),
> .string(stringKeyInstance), .integer(intIndexInstance),
> .integer(intIndexInstance), …] is simply ugly and should be hidden. Such
> API looks horrible.
>
I agree. This cries out for improvements to enums. Indeed, I have run into
the same issue with this and have a proposal idea saved up regarding
anonymous enum cases and subtyping relationships. It would not have been
in-scope for phase 1, so I did not write to the list about it. I'm short on
time these days, but eventually I'll propose it unless someone else gets to
it first. However, this problem does not justify `open` vs. `public`.


> Is this discussion really going to end with every statement being
> questioned with “why”?
>
Why not?


> Why is 42 the number that rules the universe?
>
Surely, it is for the same reason that May 25 is Towel Day.


> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 20. Februar 2017 um 00:03:44, Xiaodi Wu (xiaodi...@gmail.com) schrieb:
>
> On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev <
> adrian.zuba...@devandartist.com> wrote:
>
>> Matthew has pretty much summed up everything with a single question in
>> his last reply. It makes me tired of repeating myself over and over again.
>>
>> Here’s the challenge for you:
>>
>> Implement a subscript where the first parameter is a String (trivial),
>> but the second to n are String’s and/or Int’s. There is no restriction of
>> order for the Int’s and String’s and there could be as many as you’d like,
>> so no overloads are allowed (a hint: variadics). You should be able to use
>> variables in that subscript and literals. You’re not allowed to use enum
>> constructors
>>
> Why not? You want a parameter that takes either String or Int. In another
> language, you might express this as `String | Int`, but Chris Lattner and
> others have said on this list that enums are the intended way of expressing
> this in Swift.
>
>> and the client should not be able to extend the set of types you can pass
>> to that subscript. That said it can look like this: someInstance["key",
>> "key1", 1, stringKeyInstance, intIndexInstance, intIndexInstance, …]
>>
>> Creating hacks like unreachable types with hidden inits is prohibited.
>>
>> Have fun!
>>
>>
>> --
>> Adrian Zubarev
>> Sent with Airmail
>>
>> Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com) schrieb:
>>
>> Sorry, I have read through this thread twice and do not understand the
>> point you are making. Can you explain your example once more?
>>
>> Specifically, I do not understand why it is that your code should have
>> problems with third-party types that conform to your protocol. If your
>> protocol has requirements that third-party types cannot fulfill, then
>> naturally those requirements will prevent a third-party from conforming new
>> types to your protocol. OTOH, if your protocol does not have any
>> requirements that third-party types cannot fulfill, then your code that
>> accepts anything that conforms to your protocol should be indifferent to
>> whether the conforming type is defined by you or someone else. After all, a
>> conforming type would fulfill all the semantic and syntactic requirements
>> of the protocol! If your protocol has requirements that you are unable to
>> state in code, causing third-party types to conform that really shouldn't,
>> then that is a case for additional features that allow you to express those
>> requirements more accurately, not an argument for having protocols that
>> can't be conformed to by a third-party. What am I missing?
>>
>>
>> On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> That’s the whole point I was making. :) Thank you Matthew. That makes my
>>> example a real world example and not just some bike shedding.
>>>
>>> --
>>> Adrian Zubarev
>>> Sent with Airmail
>>>
>>> Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com)
>>> schrieb:
>>>
>>>
>>>
>>> Sent from my iPad
>>>
>>> On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> Just FYI, I solved this issue in my own library (which included a json
>>> jpointer implementation) via:
>>>
>>> public enum SubscriptParameter {
>>>   case string(String)
>>>   case int(Int)
>>> }
>>>
>>> extension SubscriptParameter : ExpressibleByIntegerLiteral {
>>>   public init(integerLiteral value: Int) {
>>> self = .int(value)
>>>   }
>>> }
>>>
>>> extension SubscriptParameter : ExpressibleByStringLiteral {
>>>   public init(stringLiteral value: String) {
>>> self = .string(value)
>>>   }
>>>   public init(extendedGraphemeClusterLiteral value: String) {
>>> self.init(stringLiteral: value)
>>>   }
>>>
>>>   public init(unicodeScalarLiteral value: String) {
>>> self.init(stringLiteral: value)
>>>   }
>>> }
>>>
>>> extension SubscriptParame

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Brent Royal-Gordon via swift-evolution
> On Feb 18, 2017, at 10:58 PM, David Waite via swift-evolution 
>  wrote:
> 
> I am unsure if this feature is a good idea. Does someone have a real-world 
> use for this which isn’t just hiding strong implementation coupling behind a 
> protocol?

Strong coupling is sometimes inevitable.

In a previous thread, I brought up an example of a place I would use this 
feature: Wrapping the SQLite APIs. For instance:

public protocol SQLiteValue {
init(statement: SQLiteStatement, columnAt index: Int) throws
func bind(to statement: SQLiteStatement, at index: Int) throws
}
extension Int: SQLiteValue {
public init(statement: SQLiteStatement, columnAt index: Int) 
throws {
self = sqlite3_column_int(statement.stmt, index)
}
public func bind(to statement: SQLiteStatement, at index: Int) 
throws {
try throwIfNotOK(
sqlite3_bind_int64(statement.stmt, index, self)
)
}
}
extension Double: SQLiteValue {…}
extension Data: SQLiteValue {…}
extension String: SQLiteValue {…}
extension Optional: SQLiteValue where Wrapped: SQLiteValue {…}

This is a case of your hated "strong implementation coupling". But the coupling 
is to a library that ultimately writes data to disk in a portable format. 
Strong coupling here is inevitable.

What is the purpose of permitting outside conformances to `SQLiteValue`? There 
is no useful way to conform to `SQLiteValue`; the underlying library supports 
certain types, and I've implemented support for those types. Allowing outside 
conformances can only mislead people into fruitlessly trying to conform their 
types, not realizing that the calls they need simply aren't exposed.

Moreover, exposing these details unnecessarily freezes the design of 
`SQLiteValue`. If I want to change the design of this parameter handling in a 
future version, well, too bad, the API is public, I'm stuck. *For an API I 
don't intend anyone to conform to publicly in the first place.* That kind of 
sucks, doesn't it?

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Pitch] Allow use associated type outside of its protocol

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 5:04 PM, 曹剑楠 via swift-evolution <
swift-evolution@swift.org> wrote:

> Hi All,
>
> I’m coding for section like data structure.
> For example:
>
> I have an Album struct, which has many MediaItems.
> It has a sectioned property called "sectionedMediaItemInfos", which is an
> array of sections.
> Each section represents for a disc, and has an "items" array contains all
> MedaItems in that disc.
>
> The define code is like:
>
> ```Swift
> public struct Album {
> public let sectionedMediaItemInfos: [Sectioned]?
> }
>
> public struct Sectioned : SectionProtocol {
> public let title: String?
> public let items: [Item]
>
>
> public init() {
> items = []
> title = nil
> }
> }
>
> public protocol SectionProtocol {
> associatedtype SectionItemType
> var items: [SectionItemType] { get }
> }
> ```
>
> Now I want to define some extra properties for sections array, like
> "sectionMediaItemInfos"."itemsCount" that count all items in each
> sections.
> So I can write that extension:
>
> ```Swift
> public extension Array where Element : SectionProtocol {
>
>
> var itemsCount: Int {
> return reduce(0) { (result, section) in result + section.items.
> count }
> }
>
> }
> ```
>
> So I can get my itemsCount with code like:
>
> ```Swift
> album.sectionedMediaItemInfos.itemsCount
> ```
>
> That looks good.
>
> Then I want to define code to return all items in this sectioned property.
>
>
> ```Swift
> public extension Array where Element : SectionProtocol {
> var items: [SectionProtocol.SectionItemType] {
> return .flatMap { $0.items }
> }
> }
> ```
>

Sorry, I'm reading this quickly, but I'm confused as to why you're not
writing `var items: [Element.SectionItemType]`. That seems to be what you
want, no? `SectionProtocol.SectionItemType` has no constraints and, even if
the grammar allowed you to write it, would have to be equivalent to `Any`.

This doesn’t work. It reported as "Cannot use associated type
> 'SectionItemType' outside of its protocol"
>
> The only way to achieve my goals is to untyped the extended "items"
> property:
>
> ```Swift
> public extension Array where Element : SectionProtocol {
> var items: [Any] {
> return self.flatMap { $0.items }
> }
> }
> ```
>
> Which is not perfect for this case.
>
>
> So in this special case, I think allow use associated type outside of its
> protocol is necessary.
>
> And we may allow define protocol with generic type. That would be more
> convenient.
>
>
> ```Swift
> public struct Album {
> public let sectionedMediaItemInfos: [Sectioned]?
> }
>
>
> public struct Sectioned : SectionProtocol {
> public let title: String?
> public let items: [Item]
>
> public init() {
> items = []
> title = nil
> }
> }
>
> public protocol SectionProtocol {
> var items: [SectionItemType] { get }
> }
>
>
> public extension Array where Element : SectionProtocol {
> var items: [Element.SectionItemType] {
> return self.flatMap { $0.items }
> }
> }
>
> ```
>
> Thank all!
>
> Jiannan
>
>
>
>
> ___
> 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] open and public protocols

2017-02-19 Thread David Hart via swift-evolution

> On 20 Feb 2017, at 00:10, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> Because someInstance["key", .string("key1"), .integer(1), 
> .string(stringKeyInstance), .integer(intIndexInstance), 
> .integer(intIndexInstance), …] is simply ugly and should be hidden. Such API 
> looks horrible.
> 
> Is this discussion really going to end with every statement being questioned 
> with “why”? Why is 42 the number that rules the universe?
> 
Lets stay polite and keep things civil.

The "the client should not be able to extend the set of types you can pass to 
that subscript.” requirement seems totally arbitrary and an anti-pattern. I’m 
perfectly happy with:

enum Key {
case string(String)
case int(Int)
}

protocol KeyConvertible {
var key: Key { get }
}

subscript(initial: String, others: KeyConvertible...) -> Foo

> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 20. Februar 2017 um 00:03:44, Xiaodi Wu (xiaodi...@gmail.com 
> ) schrieb:
> 
>> On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev 
>> mailto:adrian.zuba...@devandartist.com>> 
>> wrote:
>> Matthew has pretty much summed up everything with a single question in his 
>> last reply. It makes me tired of repeating myself over and over again.
>> 
>> Here’s the challenge for you:
>> 
>> Implement a subscript where the first parameter is a String (trivial), but 
>> the second to n are String’s and/or Int’s. There is no restriction of order 
>> for the Int’s and String’s and there could be as many as you’d like, so no 
>> overloads are allowed (a hint: variadics). You should be able to use 
>> variables in that subscript and literals. You’re not allowed to use enum 
>> constructors
>> 
>> Why not? You want a parameter that takes either String or Int. In another 
>> language, you might express this as `String | Int`, but Chris Lattner and 
>> others have said on this list that enums are the intended way of expressing 
>> this in Swift.
>> and the client should not be able to extend the set of types you can pass to 
>> that subscript. That said it can look like this: someInstance["key", "key1", 
>> 1, stringKeyInstance, intIndexInstance, intIndexInstance, …]
>> 
>> Creating hacks like unreachable types with hidden inits is prohibited.
>> 
>> Have fun!
>> 
>> 
>> 
>> -- 
>> Adrian Zubarev
>> Sent with Airmail
>> 
>> Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com 
>> ) schrieb:
>> 
>>> Sorry, I have read through this thread twice and do not understand the 
>>> point you are making. Can you explain your example once more?
>>> 
>>> Specifically, I do not understand why it is that your code should have 
>>> problems with third-party types that conform to your protocol. If your 
>>> protocol has requirements that third-party types cannot fulfill, then 
>>> naturally those requirements will prevent a third-party from conforming new 
>>> types to your protocol. OTOH, if your protocol does not have any 
>>> requirements that third-party types cannot fulfill, then your code that 
>>> accepts anything that conforms to your protocol should be indifferent to 
>>> whether the conforming type is defined by you or someone else. After all, a 
>>> conforming type would fulfill all the semantic and syntactic requirements 
>>> of the protocol! If your protocol has requirements that you are unable to 
>>> state in code, causing third-party types to conform that really shouldn't, 
>>> then that is a case for additional features that allow you to express those 
>>> requirements more accurately, not an argument for having protocols that 
>>> can't be conformed to by a third-party. What am I missing?
>>> 
>>> 
>>> On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> That’s the whole point I was making. :) Thank you Matthew. That makes my 
>>> example a real world example and not just some bike shedding.
>>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com 
>>> ) schrieb:
>>> 
 
 
 Sent from my iPad
 
 On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
 mailto:swift-evolution@swift.org>> wrote:
 
> Just FYI, I solved this issue in my own library (which included a json 
> jpointer implementation) via:
> 
> public enum SubscriptParameter {
>   case string(String)
>   case int(Int)
> }
> 
> extension SubscriptParameter : ExpressibleByIntegerLiteral {
>   public init(integerLiteral value: Int) {
> self = .int(value)
>   }
> }
> 
> extension SubscriptParameter : ExpressibleByStringLiteral {
>   public init(stringLiteral value: String) {
> self = .string(value)
>   }
>   public init(extendedGraphemeClusterLiteral value: String) {
> self.init(stringLiteral: value)
>   }
>   public init(unicodeS

Re: [swift-evolution] Dictionary Enhancements

2017-02-19 Thread Ben Cohen via swift-evolution

> On Feb 17, 2017, at 11:20 PM, David Waite  
> wrote:
> 
> 
>> On Feb 16, 2017, at 5:26 PM, Ben Cohen via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> Hi swift-evolution,
>> 
>> Following up on Ted’s post regarding the opening up of stage 2, I’m starting 
>> a thread to discuss improvements to the Dictionary type.
>> 
>> Here is a list of commonly requested changes/enhancements to Dictionary, all 
>> of which would probably be appropriate to put together into a single 
>> evolution proposal:
>> 
> 
>> Add a defaulting subscript get (e.g. counts[key, default: 0] += 1 or 
>> grouped(key, default:[]].append(value)).
> Interesting, most of my scenarios aren’t one line subscript mutations like 
> this, so I have been happy with counts[key] ?? 0, grouped(key) ?? [], etc.
> 

As well as a readability/discoverability benefit, there’s also a performance 
benefit: d[key] = (d[key] ?? []) + [value] is a linear-time operation, whereas 
d[key, default: []].append(value) should be constant time (there is some work 
needed on dictionary internals for this to work but the API ought to enable it 
once that’s done).

>> Add capacity property and reserveCapacity() method.
> would CoW copies also have the same reserved capacity?

Yes, it would mirror arrays, which behave like this. Note dictionaries already 
have this characteristic – they just don’t expose their capacity or allow you 
to preemptively expand it.

Any other behavior would be tricky. Until its mutated, a CoW copy is a literal 
copy, so must share the original’s capacity. Once the mutation forces a buffer 
copy, it would be pretty odd for that capacity to suddenly shrink.

> One way I could hypothetically copy around dictionaries that are using 
> significantly more memory than I suspected,the other way algorithms would be 
> quite confusing as an assignment to a variable might cause the capacity to 
> revert.
>  
> In terms of additional features, I have needed to group by value before, e.g. 
> turn from K->V to V -> [K], which isn’t a simple reduce statement.
> 

If there is a group-by operation from sequences, this ought to be composable 
from that given dictionaries are (Key,Value) sequences.

> -DW

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
Because someInstance["key", .string("key1"), .integer(1), 
.string(stringKeyInstance), .integer(intIndexInstance), 
.integer(intIndexInstance), …] is simply ugly and should be hidden. Such API 
looks horrible.

Is this discussion really going to end with every statement being questioned 
with “why”? Why is 42 the number that rules the universe?



-- 
Adrian Zubarev
Sent with Airmail

Am 20. Februar 2017 um 00:03:44, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev 
 wrote:
Matthew has pretty much summed up everything with a single question in his last 
reply. It makes me tired of repeating myself over and over again.

Here’s the challenge for you:

Implement a subscript where the first parameter is a String (trivial), but the 
second to n are String’s and/or Int’s. There is no restriction of order for the 
Int’s and String’s and there could be as many as you’d like, so no overloads 
are allowed (a hint: variadics). You should be able to use variables in that 
subscript and literals. You’re not allowed to use enum constructors

Why not? You want a parameter that takes either String or Int. In another 
language, you might express this as `String | Int`, but Chris Lattner and 
others have said on this list that enums are the intended way of expressing 
this in Swift.
and the client should not be able to extend the set of types you can pass to 
that subscript. That said it can look like this: someInstance["key", "key1", 1, 
stringKeyInstance, intIndexInstance, intIndexInstance, …]

Creating hacks like unreachable types with hidden inits is prohibited.

Have fun!



-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

Sorry, I have read through this thread twice and do not understand the point 
you are making. Can you explain your example once more?

Specifically, I do not understand why it is that your code should have problems 
with third-party types that conform to your protocol. If your protocol has 
requirements that third-party types cannot fulfill, then naturally those 
requirements will prevent a third-party from conforming new types to your 
protocol. OTOH, if your protocol does not have any requirements that 
third-party types cannot fulfill, then your code that accepts anything that 
conforms to your protocol should be indifferent to whether the conforming type 
is defined by you or someone else. After all, a conforming type would fulfill 
all the semantic and syntactic requirements of the protocol! If your protocol 
has requirements that you are unable to state in code, causing third-party 
types to conform that really shouldn't, then that is a case for additional 
features that allow you to express those requirements more accurately, not an 
argument for having protocols that can't be conformed to by a third-party. What 
am I missing?


On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
 wrote:
That’s the whole point I was making. :) Thank you Matthew. That makes my 
example a real world example and not just some bike shedding.

-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com) 
schrieb:



Sent from my iPad

On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
 wrote:

Just FYI, I solved this issue in my own library (which included a json jpointer 
implementation) via:

public enum SubscriptParameter {
  case string(String)
  case int(Int)
}

extension SubscriptParameter : ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    self = .int(value)
  }
}

extension SubscriptParameter : ExpressibleByStringLiteral {
  public init(stringLiteral value: String) {
    self = .string(value)
  }
  public init(extendedGraphemeClusterLiteral value: String) {
    self.init(stringLiteral: value)
  }
  public init(unicodeScalarLiteral value: String) {
    self.init(stringLiteral: value)
  }
}

extension SubscriptParameter : CustomStringConvertible {
  public var description: String {
    switch self {
    case .string(let str):
      return "\"\(str)\""
    case .int(let i):
      return String(i)
    }
  }
}

func debug(_ path:SubscriptParameter...) {
  print("path is \(path)")
}

debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]

Can you make this work with variables - not just literals - and still prevent 
users from extending the set of types and without requiring an enum case 
constructor to be used by clients?



On Feb 19, 2017, at 1:14 AM, Adrian Zubarev  
wrote:

If you haven’t followed the other thread Matthew previously opened than you 
have missed the example I showed there.

Here it is again:

public protocol SubscriptParameterType {
 
// This property was needed to prevent the client from breaking
// the library by conforming to the protocol, but I'd like to  
// keep it invisible for the client, or even better prevent the
// client from conforming to t

[swift-evolution] [Pitch] Allow use associated type outside of its protocol

2017-02-19 Thread 曹剑楠 via swift-evolution
Hi All,

I’m coding for section like data structure. 
For example:

I have an Album struct, which has many MediaItems.
It has a sectioned property called "sectionedMediaItemInfos", which is an array 
of sections.
Each section represents for a disc, and has an "items" array contains all 
MedaItems in that disc.

The define code is like:

```Swift
public struct Album {
public let sectionedMediaItemInfos: [Sectioned]?
}

public struct Sectioned : SectionProtocol {
public let title: String?
public let items: [Item]

public init() {
items = []
title = nil
}
}

public protocol SectionProtocol {
associatedtype SectionItemType
var items: [SectionItemType] { get }
}
```

Now I want to define some extra properties for sections array, like
"sectionMediaItemInfos"."itemsCount" that count all items in each sections.
So I can write that extension:

```Swift
public extension Array where Element : SectionProtocol {

var itemsCount: Int {
return reduce(0) { (result, section) in result + section.items.count }
}

}
```

So I can get my itemsCount with code like:

```Swift
album.sectionedMediaItemInfos.itemsCount
```

That looks good.

Then I want to define code to return all items in this sectioned property.


```Swift
public extension Array where Element : SectionProtocol {
var items: [SectionProtocol.SectionItemType] {
return .flatMap { $0.items }
}
}
```

This doesn’t work. It reported as "Cannot use associated type 'SectionItemType' 
outside of its protocol"

The only way to achieve my goals is to untyped the extended "items" property:

```Swift
public extension Array where Element : SectionProtocol {
var items: [Any] {
return self.flatMap { $0.items }
}
}
```

Which is not perfect for this case.


So in this special case, I think allow use associated type outside of its 
protocol is necessary.

And we may allow define protocol with generic type. That would be more 
convenient.


```Swift
public struct Album {
public let sectionedMediaItemInfos: [Sectioned]?
}


public struct Sectioned : SectionProtocol {
public let title: String?
public let items: [Item]

public init() {
items = []
title = nil
}
}

public protocol SectionProtocol {
var items: [SectionItemType] { get }
}


public extension Array where Element : SectionProtocol {
var items: [Element.SectionItemType] {
return self.flatMap { $0.items }
}
}

```

Thank all!

Jiannan



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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 4:51 PM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> Matthew has pretty much summed up everything with a single question in his
> last reply. It makes me tired of repeating myself over and over again.
>
> Here’s the challenge for you:
>
> Implement a subscript where the first parameter is a String (trivial), but
> the second to n are String’s and/or Int’s. There is no restriction of order
> for the Int’s and String’s and there could be as many as you’d like, so no
> overloads are allowed (a hint: variadics). You should be able to use
> variables in that subscript and literals. You’re not allowed to use enum
> constructors
>
Why not? You want a parameter that takes either String or Int. In another
language, you might express this as `String | Int`, but Chris Lattner and
others have said on this list that enums are the intended way of expressing
this in Swift.

> and the client should not be able to extend the set of types you can pass
> to that subscript. That said it can look like this: someInstance["key",
> "key1", 1, stringKeyInstance, intIndexInstance, intIndexInstance, …]
>
> Creating hacks like unreachable types with hidden inits is prohibited.
>
> Have fun!
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com) schrieb:
>
> Sorry, I have read through this thread twice and do not understand the
> point you are making. Can you explain your example once more?
>
> Specifically, I do not understand why it is that your code should have
> problems with third-party types that conform to your protocol. If your
> protocol has requirements that third-party types cannot fulfill, then
> naturally those requirements will prevent a third-party from conforming new
> types to your protocol. OTOH, if your protocol does not have any
> requirements that third-party types cannot fulfill, then your code that
> accepts anything that conforms to your protocol should be indifferent to
> whether the conforming type is defined by you or someone else. After all, a
> conforming type would fulfill all the semantic and syntactic requirements
> of the protocol! If your protocol has requirements that you are unable to
> state in code, causing third-party types to conform that really shouldn't,
> then that is a case for additional features that allow you to express those
> requirements more accurately, not an argument for having protocols that
> can't be conformed to by a third-party. What am I missing?
>
>
> On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> That’s the whole point I was making. :) Thank you Matthew. That makes my
>> example a real world example and not just some bike shedding.
>>
>> --
>> Adrian Zubarev
>> Sent with Airmail
>>
>> Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com)
>> schrieb:
>>
>>
>>
>> Sent from my iPad
>>
>> On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Just FYI, I solved this issue in my own library (which included a json
>> jpointer implementation) via:
>>
>> public enum SubscriptParameter {
>>   case string(String)
>>   case int(Int)
>> }
>>
>> extension SubscriptParameter : ExpressibleByIntegerLiteral {
>>   public init(integerLiteral value: Int) {
>> self = .int(value)
>>   }
>> }
>>
>> extension SubscriptParameter : ExpressibleByStringLiteral {
>>   public init(stringLiteral value: String) {
>> self = .string(value)
>>   }
>>   public init(extendedGraphemeClusterLiteral value: String) {
>> self.init(stringLiteral: value)
>>   }
>>
>>   public init(unicodeScalarLiteral value: String) {
>> self.init(stringLiteral: value)
>>   }
>> }
>>
>> extension SubscriptParameter : CustomStringConvertible {
>>   public var description: String {
>> switch self {
>> case .string(let str):
>>   return "\"\(str)\""
>> case .int(let i):
>>   return String(i)
>> }
>>   }
>> }
>>
>> func debug(_ path:SubscriptParameter...) {
>>   print("path is \(path)")
>> }
>>
>> debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]
>>
>>
>> Can you make this work with variables - not just literals - and still
>> prevent users from extending the set of types and without requiring an enum
>> case constructor to be used by clients?
>>
>>
>>
>> On Feb 19, 2017, at 1:14 AM, Adrian Zubarev <
>> adrian.zuba...@devandartist.com> wrote:
>>
>> If you haven’t followed the other thread Matthew previously opened than
>> you have missed the example I showed there.
>>
>> Here it is again:
>>
>> public protocol SubscriptParameterType {
>>
>> // This property was needed to prevent the client from breaking
>> // the library by conforming to the protocol, but I'd like to
>> // keep it invisible for the client, or even better prevent the
>> // client from conforming to the protocol.
>> var parameter: Document.SubscriptParameter { get }
>> }

[swift-evolution] [Draft] Guarded closures and `@guarded` arguments

2017-02-19 Thread Matthew Johnson via swift-evolution
I want to thank everyone who commented on the first draft of this proposal.  I 
continue to believe the basic idea is a good one but there were a number of 
problems with the details of the design presented in that draft.  They key 
insight that led to this new design is the idea of using a sigil at the usage 
site to establish different semantics than usual for guarded closures.  Special 
thanks to those of you who focused my attention on the call site.

This new draft presents a much stronger, more general design that I hope 
addresses all of the concerns expressed about the previous draft.


# Guarded Closures and `@guarded` arguments

* Proposal: [SE-](-selfsafe.md)
* Authors: [Matthew Johnson](https://github.com/anandabits)
* Review Manager: TBD
* Status: **Awaiting review**

## Introduction

Some APIs have what we might call weak callback semantics.  This design is 
common in many of Apple's newer callback APIs.  These APIs greatly reduce the 
possibility of unintentional reference cycles / leaks by guaranteeing that they 
do not extend the lifetime of the observation target.

It is possible to implement APIs with this contract in Swift today, but the is 
don't feel very natural to either library implementers, or more importantly 
library users.  It should be possible to design an API with this important 
semantic contract that feels natural to use (and implement) in Swift.

This proposal introduces guarded closures (prefixed with a `?` sigil).  
Closures that use this sigil default to capturing any references as `weak` and 
guard the invocation to be a no-op if any of the guarded references have been 
released before it is invoked.  If no captured references have been invoked, 
they are upgraded to strong references for the duration of the invocation.  
This provides syntactic sugar for a very common pattern in Swift code 
(sometimes called the weak self / strong self dance).

It also introduces `@guarded` as an annotation that can be used on parameters 
of function type.  Users are required to use a guarded closure when providing 
an argument for a `@guarded` parameter.  This annotation is will be used in 
cases where it is *usually* (not always) wrong for the argument to extend the 
lifetime of objects that might be captured by the arguemnt it is given.  This 
is a generalization of weak callback semantics that this proposal calls guarded 
callback semantics.

An early version of this proposal was discussed in the thread: [`@selfsafe`: a 
new way to avoid reference 
cycles](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032374.html)

## Motivation

Accidentally forgeting to use weak references is a common problem and can 
easily lead to reference cycles.  Some APIs (such as many kinds of callbacks / 
notifications / observers) are best designed such that users cannot extend the 
lifetime of objects captured by the function argument they are given (unless 
the user explicitly goes out of their way to state their intent to do so).

For example, `UIControl.addTarget(_:action:for:) does not retain the target, 
thereby preventing users from making the mistake of using a closure with an 
accidental strong reference.  We can do something similar in Swift:

```swift
// in the library:
func addTarget(_ target: T, action: T -> Int -> Void) {
  // store a weak reference to the target
  // when the action is fired call ref.map{ action($0)(42) }
}

// in user code:
class C {
  init() {
 addTarget(self, action: C.takesInt)
  }

  func takesInt(_ i: Int) {}
}
```

Both the library and the caller have to deal with a lot of details and 
boilerplate that we would prefer to avoid.  The natural design in Swift would 
be to simply take an action function.  Unfortunately if we do that we run into 
a problem:

```swift
// in the library
func addAction(_ f: Int -> Void) {
  // store a strong ref to f, which might include a strong ref to a captured 
self
  // later when the action is fired call f(42)
}

// in user code
class C {
  init() {
 addAction(takesInt)
 // oops! should have been: addAction{ [weak self] self?.takesInt($0) }
  }

  func takesInt(_ i: Int) {}
}
```

Here the syntax is much nicer, but unfortunately we have unintentionally 
extended the lifetime of `self`.  The burden of ensuring `self` is not captured 
or is captured weakly falls on users of the library.

It would very nice if it were possible to design an API that has weak or 
guarded callback semantics while still acheiving the more concise and Swifty 
syntax.

## Proposed solution

This proposal introduces guarded closures and the `@guarded` annotation for 
arguments of function type.

### Guarded Closures

A guarded closure can be created in two ways, both of which use the `?` sigil.  
The `?` sigil was selected because of it's relationship to `Optional` and to 
optional chaining.

First, the guarded captures are weak references with `Optional` type.

Second, anything following a `?` in an optional chain

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
On Sun, Feb 19, 2017 at 4:46 PM, Karl Wagner  wrote:

>
> > On 19 Feb 2017, at 23:24, Xiaodi Wu via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Sorry, I have read through this thread twice and do not understand the
> point you are making. Can you explain your example once more?
> >
> > Specifically, I do not understand why it is that your code should have
> problems with third-party types that conform to your protocol. If your
> protocol has requirements that third-party types cannot fulfill, then
> naturally those requirements will prevent a third-party from conforming new
> types to your protocol. OTOH, if your protocol does not have any
> requirements that third-party types cannot fulfill, then your code that
> accepts anything that conforms to your protocol should be indifferent to
> whether the conforming type is defined by you or someone else. After all, a
> conforming type would fulfill all the semantic and syntactic requirements
> of the protocol! If your protocol has requirements that you are unable to
> state in code, causing third-party types to conform that really shouldn't,
> then that is a case for additional features that allow you to express those
> requirements more accurately, not an argument for having protocols that
> can't be conformed to by a third-party. What am I missing?
> >
>
> I see it as an API expressivity thing; it’s not that clients _can’t_
> technically conform to the protocol, it’s that they _shouldn’t_ because
> that’s not why I’m exposing it.
>
> There are protocols that you do expose because you expect others to
> conform to them. There are others which you only expect to be used as
> generic/existential constraints.
>
> That’s basically the same reasoning as having a distinction between
> public/open for classes, too;


It isn't. The text of the proposal spends several paragraphs motivating the
distinction between public and open classes in the following way:

"A subclass that overrides methods of its superclass is intricately
intertwined with it. The two systems are not composed, and their behavior
cannot be understood independently. [...] Subclasses cannot be
independently tested using a mocked implementation of the superclass or
composed to apply the customizations of two different subclasses to a
single instance."

This is in direct contradistinction to protocols. Protocols *are* meant to
be composed. While a type is meant to uphold the semantic guarantees of
protocols to which it conforms, the behavior of a protocol and its
conforming types *are* meant to be understood independently. Conforming
types *are* meant to be testable independently from the protocols to which
they conform.


before we had “open” as a separate thing, you could subclass anything that
> was public. There was extra motivation for classes because of the
> opportunities for the optimiser to devirtualise function calls which may
> not be as strong a factor for protocols, but from an API design perspective
> it’s still nice to have consistent capabilities. From looking at my own
> code, I know that marking-up protocols which clients can conform to with
> @open would make both of our lives easier.
>
> I wouldn’t mind if we allowed the compiler to not enforce this rule very
> strongly (e.g. with a suppressible warning). Depends on what is achievable.
>
> - Karl
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
Matthew has pretty much summed up everything with a single question in his last 
reply. It makes me tired of repeating myself over and over again.

Here’s the challenge for you:

Implement a subscript where the first parameter is a String (trivial), but the 
second to n are String’s and/or Int’s. There is no restriction of order for the 
Int’s and String’s and there could be as many as you’d like, so no overloads 
are allowed (a hint: variadics). You should be able to use variables in that 
subscript and literals. You’re not allowed to use enum constructors and the 
client should not be able to extend the set of types you can pass to that 
subscript. That said it can look like this: someInstance["key", "key1", 1, 
stringKeyInstance, intIndexInstance, intIndexInstance, …]

Creating hacks like unreachable types with hidden inits is prohibited.

Have fun!



-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 23:25:11, Xiaodi Wu (xiaodi...@gmail.com) schrieb:

Sorry, I have read through this thread twice and do not understand the point 
you are making. Can you explain your example once more?

Specifically, I do not understand why it is that your code should have problems 
with third-party types that conform to your protocol. If your protocol has 
requirements that third-party types cannot fulfill, then naturally those 
requirements will prevent a third-party from conforming new types to your 
protocol. OTOH, if your protocol does not have any requirements that 
third-party types cannot fulfill, then your code that accepts anything that 
conforms to your protocol should be indifferent to whether the conforming type 
is defined by you or someone else. After all, a conforming type would fulfill 
all the semantic and syntactic requirements of the protocol! If your protocol 
has requirements that you are unable to state in code, causing third-party 
types to conform that really shouldn't, then that is a case for additional 
features that allow you to express those requirements more accurately, not an 
argument for having protocols that can't be conformed to by a third-party. What 
am I missing?


On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
 wrote:
That’s the whole point I was making. :) Thank you Matthew. That makes my 
example a real world example and not just some bike shedding.

-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com) 
schrieb:



Sent from my iPad

On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
 wrote:

Just FYI, I solved this issue in my own library (which included a json jpointer 
implementation) via:

public enum SubscriptParameter {
  case string(String)
  case int(Int)
}

extension SubscriptParameter : ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    self = .int(value)
  }
}

extension SubscriptParameter : ExpressibleByStringLiteral {
  public init(stringLiteral value: String) {
    self = .string(value)
  }
  public init(extendedGraphemeClusterLiteral value: String) {
    self.init(stringLiteral: value)
  }
  public init(unicodeScalarLiteral value: String) {
    self.init(stringLiteral: value)
  }
}

extension SubscriptParameter : CustomStringConvertible {
  public var description: String {
    switch self {
    case .string(let str):
      return "\"\(str)\""
    case .int(let i):
      return String(i)
    }
  }
}

func debug(_ path:SubscriptParameter...) {
  print("path is \(path)")
}

debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]

Can you make this work with variables - not just literals - and still prevent 
users from extending the set of types and without requiring an enum case 
constructor to be used by clients?



On Feb 19, 2017, at 1:14 AM, Adrian Zubarev  
wrote:

If you haven’t followed the other thread Matthew previously opened than you 
have missed the example I showed there.

Here it is again:

public protocol SubscriptParameterType {

// This property was needed to prevent the client from breaking
// the library by conforming to the protocol, but I'd like to 
// keep it invisible for the client, or even better prevent the
// client from conforming to the protocol.
var parameter: Document.SubscriptParameter { get }
}

extension Document {

public enum SubscriptParameter {

case string(String)
case integer(Int)
}
}

extension String : SubscriptParameterType {

public var parameter: Document.SubscriptParameter {

return .string(self)
}
}

extension Int : SubscriptParameterType {

public var parameter: Document.SubscriptParameter {

return .integer(self)
}
}

// Somewhere inside the `Document` type
public subscript(firstKey: String, parameters: SubscriptParameterType...) -> 
Value? { … }
The absence of closed protocols forced me to create a special requirement on 
that protocol to pr

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Karl Wagner via swift-evolution

> On 19 Feb 2017, at 23:24, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> Sorry, I have read through this thread twice and do not understand the point 
> you are making. Can you explain your example once more?
> 
> Specifically, I do not understand why it is that your code should have 
> problems with third-party types that conform to your protocol. If your 
> protocol has requirements that third-party types cannot fulfill, then 
> naturally those requirements will prevent a third-party from conforming new 
> types to your protocol. OTOH, if your protocol does not have any requirements 
> that third-party types cannot fulfill, then your code that accepts anything 
> that conforms to your protocol should be indifferent to whether the 
> conforming type is defined by you or someone else. After all, a conforming 
> type would fulfill all the semantic and syntactic requirements of the 
> protocol! If your protocol has requirements that you are unable to state in 
> code, causing third-party types to conform that really shouldn't, then that 
> is a case for additional features that allow you to express those 
> requirements more accurately, not an argument for having protocols that can't 
> be conformed to by a third-party. What am I missing?
> 

I see it as an API expressivity thing; it’s not that clients _can’t_ 
technically conform to the protocol, it’s that they _shouldn’t_ because that’s 
not why I’m exposing it.

There are protocols that you do expose because you expect others to conform to 
them. There are others which you only expect to be used as generic/existential 
constraints.

That’s basically the same reasoning as having a distinction between public/open 
for classes, too; before we had “open” as a separate thing, you could subclass 
anything that was public. There was extra motivation for classes because of the 
opportunities for the optimiser to devirtualise function calls which may not be 
as strong a factor for protocols, but from an API design perspective it’s still 
nice to have consistent capabilities. From looking at my own code, I know that 
marking-up protocols which clients can conform to with @open would make both of 
our lives easier.

I wouldn’t mind if we allowed the compiler to not enforce this rule very 
strongly (e.g. with a suppressible warning). Depends on what is achievable.

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread David Hart via swift-evolution

> On 19 Feb 2017, at 23:24, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> Sorry, I have read through this thread twice and do not understand the point 
> you are making. Can you explain your example once more?
> 
> Specifically, I do not understand why it is that your code should have 
> problems with third-party types that conform to your protocol. If your 
> protocol has requirements that third-party types cannot fulfill, then 
> naturally those requirements will prevent a third-party from conforming new 
> types to your protocol. OTOH, if your protocol does not have any requirements 
> that third-party types cannot fulfill, then your code that accepts anything 
> that conforms to your protocol should be indifferent to whether the 
> conforming type is defined by you or someone else. After all, a conforming 
> type would fulfill all the semantic and syntactic requirements of the 
> protocol! If your protocol has requirements that you are unable to state in 
> code, causing third-party types to conform that really shouldn't, then that 
> is a case for additional features that allow you to express those 
> requirements more accurately, not an argument for having protocols that can't 
> be conformed to by a third-party. What am I missing?

Yeah, sums up my opinion pretty accurately.

> On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> That’s the whole point I was making. :) Thank you Matthew. That makes my 
> example a real world example and not just some bike shedding.
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com 
> ) schrieb:
> 
>> 
>> 
>> Sent from my iPad
>> 
>> On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>>> Just FYI, I solved this issue in my own library (which included a json 
>>> jpointer implementation) via:
>>> 
>>> public enum SubscriptParameter {
>>>   case string(String)
>>>   case int(Int)
>>> }
>>> 
>>> extension SubscriptParameter : ExpressibleByIntegerLiteral {
>>>   public init(integerLiteral value: Int) {
>>> self = .int(value)
>>>   }
>>> }
>>> 
>>> extension SubscriptParameter : ExpressibleByStringLiteral {
>>>   public init(stringLiteral value: String) {
>>> self = .string(value)
>>>   }
>>>   public init(extendedGraphemeClusterLiteral value: String) {
>>> self.init(stringLiteral: value)
>>>   }
>>>   public init(unicodeScalarLiteral value: String) {
>>> self.init(stringLiteral: value)
>>>   }
>>> }
>>> 
>>> extension SubscriptParameter : CustomStringConvertible {
>>>   public var description: String {
>>> switch self {
>>> case .string(let str):
>>>   return "\"\(str)\""
>>> case .int(let i):
>>>   return String(i)
>>> }
>>>   }
>>> }
>>> 
>>> func debug(_ path:SubscriptParameter...) {
>>>   print("path is \(path)")
>>> }
>>> 
>>> debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]
>> 
>> Can you make this work with variables - not just literals - and still 
>> prevent users from extending the set of types and without requiring an enum 
>> case constructor to be used by clients?
>> 
>> 
>>> 
 On Feb 19, 2017, at 1:14 AM, Adrian Zubarev 
 mailto:adrian.zuba...@devandartist.com>> 
 wrote:
 
 If you haven’t followed the other thread Matthew previously opened than 
 you have missed the example I showed there.
 
 Here it is again:
 
 public protocol SubscriptParameterType {

 // This property was needed to prevent the client from breaking
 // the library by conforming to the protocol, but I'd like to
 // keep it invisible for the client, or even better prevent the
 // client from conforming to the protocol.
 var parameter: Document.SubscriptParameter { get }
 }
 
 extension Document {

 public enum SubscriptParameter {

 case string(String)
 case integer(Int)
 }
 }
 
 extension String : SubscriptParameterType {

 public var parameter: Document.SubscriptParameter {

 return .string(self)
 }
 }
 
 extension Int : SubscriptParameterType {

 public var parameter: Document.SubscriptParameter {

 return .integer(self)
 }
 }
 
 // Somewhere inside the `Document` type
 public subscript(firstKey: String, parameters: SubscriptParameterType...) 
 -> Value? { … }
 The absence of closed protocols forced me to create a special requirement 
 on that protocol to prevent the client from conforming to that protocol 
 and passing instances of other types my API wouldn’t want to deal with. 
 That creates unnecessary copies and I need to unpack the enum payload to 
 find out 

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Xiaodi Wu via swift-evolution
Sorry, I have read through this thread twice and do not understand the
point you are making. Can you explain your example once more?

Specifically, I do not understand why it is that your code should have
problems with third-party types that conform to your protocol. If your
protocol has requirements that third-party types cannot fulfill, then
naturally those requirements will prevent a third-party from conforming new
types to your protocol. OTOH, if your protocol does not have any
requirements that third-party types cannot fulfill, then your code that
accepts anything that conforms to your protocol should be indifferent to
whether the conforming type is defined by you or someone else. After all, a
conforming type would fulfill all the semantic and syntactic requirements
of the protocol! If your protocol has requirements that you are unable to
state in code, causing third-party types to conform that really shouldn't,
then that is a case for additional features that allow you to express those
requirements more accurately, not an argument for having protocols that
can't be conformed to by a third-party. What am I missing?


On Sun, Feb 19, 2017 at 11:53 AM, Adrian Zubarev via swift-evolution <
swift-evolution@swift.org> wrote:

> That’s the whole point I was making. :) Thank you Matthew. That makes my
> example a real world example and not just some bike shedding.
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com)
> schrieb:
>
>
>
> Sent from my iPad
>
> On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Just FYI, I solved this issue in my own library (which included a json
> jpointer implementation) via:
>
> public enum SubscriptParameter {
>   case string(String)
>   case int(Int)
> }
>
> extension SubscriptParameter : ExpressibleByIntegerLiteral {
>   public init(integerLiteral value: Int) {
> self = .int(value)
>   }
> }
>
> extension SubscriptParameter : ExpressibleByStringLiteral {
>   public init(stringLiteral value: String) {
> self = .string(value)
>   }
>   public init(extendedGraphemeClusterLiteral value: String) {
> self.init(stringLiteral: value)
>   }
>
>   public init(unicodeScalarLiteral value: String) {
> self.init(stringLiteral: value)
>   }
> }
>
> extension SubscriptParameter : CustomStringConvertible {
>   public var description: String {
> switch self {
> case .string(let str):
>   return "\"\(str)\""
> case .int(let i):
>   return String(i)
> }
>   }
> }
>
> func debug(_ path:SubscriptParameter...) {
>   print("path is \(path)")
> }
>
> debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]
>
>
> Can you make this work with variables - not just literals - and still
> prevent users from extending the set of types and without requiring an enum
> case constructor to be used by clients?
>
>
>
> On Feb 19, 2017, at 1:14 AM, Adrian Zubarev  com> wrote:
>
> If you haven’t followed the other thread Matthew previously opened than
> you have missed the example I showed there.
>
> Here it is again:
>
> public protocol SubscriptParameterType {
>
> // This property was needed to prevent the client from breaking
> // the library by conforming to the protocol, but I'd like to
> // keep it invisible for the client, or even better prevent the
> // client from conforming to the protocol.
> var parameter: Document.SubscriptParameter { get }
> }
>
> extension Document {
>
> public enum SubscriptParameter {
>
> case string(String)
> case integer(Int)
> }
> }
>
> extension String : SubscriptParameterType {
>
> public var parameter: Document.SubscriptParameter {
>
> return .string(self)
> }
> }
>
> extension Int : SubscriptParameterType {
>
> public var parameter: Document.SubscriptParameter {
>
> return .integer(self)
> }
> }
>
> // Somewhere inside the `Document` type
> public subscript(firstKey: String, parameters: SubscriptParameterType...) -> 
> Value? { … }
>
> The absence of closed protocols forced me to create a special requirement
> on that protocol to prevent the client from conforming to that protocol and
> passing instances of other types my API wouldn’t want to deal with. That
> creates unnecessary copies and I need to unpack the enum payload to find
> out which type the user passed. Instead I could simply close the protocol,
> wouldn’t need the requirement to exist and I could simply cast the type to
>  String or Int when needed.
>
> That implementation enables more safe queries of my Document type like
>
> document["key1", intIndexInstance, stringKeyInstance, 10, "key"]
>
> rather than
>
> document["key1/\(intIndexInstance)/\(stringKeyInstance)/10/key"].
> --
>
> Here is a list of hidden and semi-hidden protocols from the standard
> library that could be closed. Formatted version: https://gist.github.
> com/DevAndArtist/168c800

Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Howard Lovatt via swift-evolution
> The review of "SE-0155: Normalize Enum Case Representation" begins now and
> runs through next Friday, February 26th. The proposal is available here:
>
> https://github.com/apple/swift-evolution/blob/master/proposals/0155-normalize-enum-case-representation.md
>
> • What is your evaluation of the proposal?
>

Well worth while

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

Yes, it is confusing to have different rules

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

Yes, unification of concepts is part of the updating of Swift

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

No

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

Quick read of the proposal

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


Re: [swift-evolution] [swift-users] Plan to move swift-evolution and swift-users mailing lists to Discourse

2017-02-19 Thread David Sweeris via swift-evolution


Sent from my iPhone

> On Feb 19, 2017, at 13:41, Lane Schwartz via swift-users 
>  wrote:
> 
> Hi all,
> 
> I'm sure there are good reasons for this switch. Personally, I strongly 
> prefer email lists to forums. 
> 
> This move will make it harder for me to participate in future discussions and 
> I will be less inclined to take the effort to sign into a forum do so.
> 
> Is there a plan to enable an integrated mailing list functionality so that 
> those of us who prefer that modality can continue to participate via email? 
> Other forum software that I've been asked to use in the past (sorry, I can't 
> remember the name) had this functionality, and it made a huge difference for 
> me.

AFAIK, the plan is to not switch unless the mailing list functionality can be 
kept.

(I'm not an official source or anything, that's just the impression I got)

- Dave Sweeris 


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


Re: [swift-evolution] [Pitch] Refactor Metatypes

2017-02-19 Thread Adrian Zubarev via swift-evolution
https://github.com/DevAndArtist/swift-evolution/blob/metatypes/proposals/0126-refactor-metatypes.md


-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 22:59:18, David Hart (da...@hartbit.com) schrieb:

Where can I find a link to an updated version?

On 19 Feb 2017, at 21:42, Adrian Zubarev via swift-evolution 
 wrote:

We added a note to the proposal:

Both Type and AnyType will be declared in the Swift standard library even 
if part of the implementation might be compiler magic. That move is really 
important to allow developers to created custom nested types named as Type. 
ModuleName.TypeName.Type is ambigious today, but will become possible after 
this proposal. That means Type and AnyType will be shortcuts for 
Swift.Type and Swift.AnyType.
We also think that the proposal is ready for the review. :)




-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 09:40:19, Adrian Zubarev 
(adrian.zuba...@devandartist.com) schrieb:

Actually Brent has just now convinced me that Metatype would be a bad name to 
choose. So forget what I said in my last messages.



-- 
Adrian Zubarev
Sent with Airmail

Am 18. Februar 2017 um 17:55:33, Adrian Zubarev 
(adrian.zuba...@devandartist.com) schrieb:

The problem I was describing is about nested types named .Type, indeed. 
Assuming the proposal would go with Type, then it means you _might_ be able 
to create nested types called Type, but you always would need to call if 
through the whole namespace (e.g. A.B.Type). That is a huge downside.

Metatype on the other hand describes exactly what that _thing_ really is.

Currently on a different branch I added this important note to the 
alternatives, but I’d rather use these types for the whole proposal.

Assuming that the accepted proposal decides to use Metatype, AnyMetatype 
over Type and AnyType would imply that the type Type would no longer be 
ambiguous to use in custome modules. However, such naming choice will affect 
the type(of:) function. It might be necessary to align the function name to 
metatype(of:) to avoid any confusion, which will result in another breaking 
change. Alternatively we could leave the function as func type(of instance: 
T) -> AnyMetatype.
If we’re going for breaking changes again than I’d prefer to align the magical 
type(of:) function to metatype(of:).

I’d love to hear more input on this.



-- 
Adrian Zubarev
Sent with Airmail

Am 18. Februar 2017 um 17:00:27, Anton Zhilin (antonyzhi...@gmail.com) schrieb:

Type is a bad name for a public type: FooType is almost always a better name. 
Libraries that describe “just types”, Swift types, can as well use Metatype or 
Mirror or something.
For nested types, like Foo.Type, in the meaning of “type of Foo“, Type can’t be 
used even now.
I’d give up on Type name for the greater future of metatypes.

2017-02-18 16:28 GMT+03:00 Adrian Zubarev :


Personally I’d prefer Metatype and AnyMetatype to get rid of the 
restriction where you mostly cannot create custom types called Type, which 
annoys me a lot. Sometimes Kind as a good workaround but there are times where 
Kind doesn’t fit. :/



___
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] Refactor Metatypes

2017-02-19 Thread David Hart via swift-evolution
Where can I find a link to an updated version?

> On 19 Feb 2017, at 21:42, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> We added a note to the proposal:
> 
> Both Type and AnyType will be declared in the Swift standard library 
> even if part of the implementation might be compiler magic. That move is 
> really important to allow developers to created custom nested types named as 
> Type. ModuleName.TypeName.Type is ambigious today, but will become possible 
> after this proposal. That means Type and AnyType will be shortcuts for 
> Swift.Type and Swift.AnyType.
> We also think that the proposal is ready for the review. :)
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 19. Februar 2017 um 09:40:19, Adrian Zubarev 
> (adrian.zuba...@devandartist.com ) 
> schrieb:
> 
>> Actually Brent has just now convinced me that Metatype would be a bad name 
>> to choose. So forget what I said in my last messages.
>> 
>> 
>> 
>> -- 
>> Adrian Zubarev
>> Sent with Airmail
>> 
>> Am 18. Februar 2017 um 17:55:33, Adrian Zubarev 
>> (adrian.zuba...@devandartist.com ) 
>> schrieb:
>> 
>>> The problem I was describing is about nested types named .Type, indeed. 
>>> Assuming the proposal would go with Type, then it means you _might_ be 
>>> able to create nested types called Type, but you always would need to call 
>>> if through the whole namespace (e.g. A.B.Type). That is a huge downside.
>>> 
>>> Metatype on the other hand describes exactly what that _thing_ really is.
>>> 
>>> Currently on a different branch I added this important note to the 
>>> alternatives, but I’d rather use these types for the whole proposal.
>>> 
>>> Assuming that the accepted proposal decides to use Metatype, 
>>> AnyMetatype over Type and AnyType would imply that the type Type 
>>> would no longer be ambiguous to use in custome modules. However, such 
>>> naming choice will affect the type(of:) function. It might be necessary to 
>>> align the function name to metatype(of:) to avoid any confusion, which will 
>>> result in another breaking change. Alternatively we could leave the 
>>> function as func type(of instance: T) -> AnyMetatype.
>>> If we’re going for breaking changes again than I’d prefer to align the 
>>> magical type(of:) function to metatype(of:).
>>> 
>>> I’d love to hear more input on this.
>>> 
>>> 
>>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> Am 18. Februar 2017 um 17:00:27, Anton Zhilin (antonyzhi...@gmail.com 
>>> ) schrieb:
>>> 
 
 Type is a bad name for a public type: 
 FooType is almost always a better name. Libraries that describe “just 
 types”, Swift types, can as well use 
 Metatype or 
 Mirror or something.
 For nested types, like 
 Foo.Type, in the meaning of “type of 
 Foo“, 
 Type can’t be used even now.
 I’d give up on 
 Type name for the greater future of metatypes.
 
 2017-02-18 16:28 GMT+03:00 Adrian Zubarev >>> >:
 
 
 Personally I’d prefer Metatype and AnyMetatype to get rid of the 
 restriction where you mostly cannot create custom types called Type, which 
 annoys me a lot. Sometimes Kind as a good workaround but there are times 
 where Kind doesn’t fit. :/
 
 
>>> 
>> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Erica Sadun via swift-evolution

> On Feb 19, 2017, at 12:49 PM, Matthew Johnson via swift-evolution 
>  wrote:
> 
>> 
>> On Feb 18, 2017, at 10:49 PM, Dave Abrahams via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> I'm on vacation and don't have time for a full review right now, but I am 
>> concerned that wild this proposal would make enums more general and uniform 
>> with the rest of the language , they also would become much more awkward for 
>> common use cases. I have recently been very pleased that I didn't have to 
>> supply labels in switch statements where the label name would simply have 
>> matched the name of the variable to be bound.  This looks needlessly verbose:
>> 
>>   case .valid(value: let value, resumptionPoint: let resumptionPoint):
>> 
>> I cannot imagine a real life use case where one would have labels in the 
>> case and desire to bind associated values to variables having different 
>> names than the labels.

Dave has a good point here. (Which I'm reading *after* sending feedback to 
John.) If 
the problem with labels is that using them for conditional binding is awkward, 
maybe 
it's not the labels that's the problem. 

Pattern matching with conditional binding is a mess. 

* It's hard to read. 
* It uses inconsistent `let` and `var` both inside and outside the `case` 
syntax.
* It uses inconsistent syntax for switch/case, if/case-guard/case, and regular 
pattern matching.
* Conditional binding is coequal with pattern matching and can be 
mixed-and-matched, 
  for example, `case .foo(var x, 0 ... .max) where  x % 2 == 1`
* It involves inconsistent operators (`=` and `~=`) and awkward syntax. 
* It is hard to teach, to learn, and is one of the overall sore points of the 
language.

Some problems go away if you bind the existing value to a specific case instead 
of
conditionally binding new values. There are some significant issues here, but 
let me 
demonstrate to give a sense of what I'm talking about. An approach something 
like
the following would support this proposal and avoids DRY violations.  (I'm not
sure if this is even possible to accomplish):

```swift
enum Result {
case success(value: T)
case failure(error: Error)
}

if case let returnedResult ~= .success {
// returnedResult is the `success` case.
print(returnedResult.value) // member access
}

guard case var returnedResult ~= .success  else { ...discard error and leave 
scope ... }
// returnedResult is the `success` case for the remainder of this scope
print(returnedResult.value)

switch returnedResult {
   // Something like this
case .success:  // use $0.value
}

switch aDifferentEnum {
case foo(x: _, y: 0 ...max) where $0.x %2 == 1: // use $0.x, $0.y
case foo: // use $0.x, $0.y here
}
```

Can we support labels and re-architect interpretation/binding?

-- E


> I agree with this, but I think it’s an issue we can solve (perhaps as an 
> amendment to this proposal).
> 
> First, I think Brent’s idea of introducing an argument label that can be 
> distinct from the “property” name of the case is a good one.  I think we 
> should do this.  It takes the parallel with function signatures even further.
> 
> Second, we should allow the “property” name to be `_`.  This would mean no 
> label can be used when matching:
> 
> case valid(value _: ValueType, resumptionPoint _: PointType)
> 
> Third, I think we should also allow suers to elide the label if they either 
> discard the value with `_` or bind a name that is identical to the label, so 
> we might have:
> 
> // declaration:
> case valid(externalCasConstructorLabel value: ValueType, 
> externalCaseConstructorLabel resumptionPoint: PointType)
> 
> // match ok:
> case .valid(let value, let resumptionPoint):
> 
> // error, names do not match:
> case .valid(let foo, let bar):
> 
> // ok, label is used:
> case .valid(value: let foo, resumptionPoint: let bar):
> 
> This follows the behavior of function signatures very closely.  The external 
> label is used to provide context for the argument at the call site (of the 
> case constructor).  The internal name is used to bind a name to the value 
> that is used by code that works with the value.  
> 
> The only exception here is that because the usage site is distant from the 
> case declaration it may wish to use a different name.  We allow that, but 
> only if the “internal name” is also used in the pattern.  This preserves the 
> ability of a reader of the code to see the name / meaning of the associated 
> value as it was declared by the enum in addition to the name that might make 
> more sense for use in the local context.
> 



>> 
>> Secondly, I can't imagine a case where one would want to use the same case 
>> basename and different labels. The very common use case where the types of 
>> associated values completely distinguish the case and one would rather not 
>> have to supply a case name at all is completely unaddressed. If my quick 
>> read is not mistaken, this proposal makes it legal for cases 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Jacob Bandes-Storch via swift-evolution
On Sat, Feb 18, 2017 at 8:49 PM, Dave Abrahams via swift-evolution <
swift-evolution@swift.org> wrote:

> I'm on vacation and don't have time for a full review right now, but I am
> concerned that wild this proposal would make enums more general and uniform
> with the rest of the language , they also would become much more awkward
> for common use cases. I have recently been very pleased that I didn't have
> to supply labels in switch statements where the label name would simply
> have matched the name of the variable to be bound.  This looks needlessly
> verbose:
>
>   case .valid(value: let value, resumptionPoint: let resumptionPoint):
>
> I cannot imagine a real life use case where one would have labels in the
> case and desire to bind associated values to variables having different
> names than the labels.
>

What about something like this? It's a bit contrived, but the point is you
could easily expect to work with more than one value of the same enum type
at the same time.

enum Color {
  case rgb(red: Double, green: Double, blue: Double)
  ...

  func interpolated(to other: Color, by fraction: Double) -> Color {
switch (self, other) {
case (.rgb(red: let red, blue: let blue, green: let green),
  .rgb(red: let otherRed, blue: let otherBlue, green: let
otherGreen)):
  return .rgb(
red: lerp(from: red, to: otherRed, by: fraction),
...)
...
}
  }
}


Your point, though, reminds me of ES6 destructuring assignment, e.g. "let
{red, green} = color", and inversely a syntax whose name I don't know, "let
color = {red, green}", which are indeed quite convenient when variable
names match object key names.



> Secondly, I can't imagine a case where one would want to use the same case
> basename and different labels. The very common use case where the types of
> associated values completely distinguish the case and one would rather not
> have to supply a case name at all is completely unaddressed. If my quick
> read is not mistaken, this proposal makes it legal for cases to have
> different *complete names* (including base name and labels), but doesn't
> make it legal to have the same full name (which I would love to be "_" or
> missing in some cases) with different associated value types. If we were
> truly following the precedent set by function signatures, wouldn't that be
> possible too?
>
> Sent from my moss-covered three-handled family gradunza
>
> On Feb 17, 2017, at 5:26 PM, John McCall  wrote:
>
> Hello Swift community,
>
> The review of "SE-0155: Normalize Enum Case Representation" begins now and
> runs through next Friday, February 26th. The proposal is available here:
> https://github.com/apple/swift-evolution/blob/master/proposa
> ls/0155-normalize-enum-case-representation.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. When replying, please try to keep the proposal link at the
> top of the message:
>
> Proposal link: https://github.com/apple/swift-evolution/blob/master/
> proposals/0155-normalize-enum-case-representation.md
>
> Reply text
>
> Other replies
>
> *What goes into a review?*
>
> The goal of the review process is to improve the proposal under review
> through constructive criticism and, eventually, determine the direction of
> Swift. When writing your review, here are some questions you might want to
> answer in your review:
>
> • What is your evaluation of the proposal?
> • Is the problem being addressed significant enough to warrant a change to
> Swift?
> • Does this proposal fit well with the feel and direction of Swift?
> • If you have used other languages or libraries with a similar feature,
> how do you feel that this proposal compares to those?
> • How much effort did you put into your review? A glance, a quick reading,
> or an in-depth study?
>
> More information about the Swift evolution process is available at
> https://github.com/apple/swift-evolution/blob/master/process.md
>
> Thank you,
>
> John McCall
> Review Manager
>
> ___
> swift-evolution-announce mailing list
> swift-evolution-annou...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution-announce
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0154: Provide Custom Collections for Dictionary Keys and Values

2017-02-19 Thread Dimitri Racordon via swift-evolution
> What is your evaluation of the proposal?

+1

Nevertheless it’s a bit unclear to me what is the impact of these additional 
collections on the ownership of the dictionary.

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

Yes.

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

Python 3 addressed this issue (w.r.t Python 2) in a similar way, using 
dict_[keys|values] objects. It is common in that language to manipulate the 
dict_keys. As they are set-like structures, it allows to efficiently manipulate 
the keys of a dictionary prior to its access/modification.
The proposal doesn’t elaborate on the use of 

I feel like the proposal’s Dictionary.Keys could benefit from a similar 
approach, not limiting itself to conforming to Collection.

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

A careful reading.

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


Re: [swift-evolution] A concern

2017-02-19 Thread Derrick Ho via swift-evolution
The first time I read through the swift manual. I thought to myself, "swift
is Apples version of C++"

The book on c -- the C programming language by Brian kernighan -- is around
200 pages.

As for objective c I've yet to see a book that covers more than a single
chapter Before diving into cocoa frameworks.

Big c++ was around 2000 pages, maybe more. Swift's book was around that
size as well. It is huge...

Both are huge. Maybe the ability to be jack of all trades makes for a
dominant language. Kind of like English. It borrows from so many languages
but as a result has universal appeal.

Swift may become modern day c++


On Sun, Feb 19, 2017 at 3:35 PM Dimitri Racordon via swift-evolution <
swift-evolution@swift.org> wrote:

> Very interesting topic!
>
> I disagree with the premise. Without having written a single line of
> Objective-C (nor Cocoa), I was able to get started with Swift in maybe 2
> busy nights. Advanced concepts are difficult to master, but imho the
> learning curve is not that steep.
>
> There are experts in every languages used in the industry, because actual
> production-ready applications often required experts. That is not to say
> that all languages are born equal, but my belief is that if the complexity
> isn’t in the language, then it’s somehow pushed into the libraries. In that
> case, being an expert isn’t really about mastering the language, but rather
> about mastering all the intricacies of its mainstream libraries (J2EE, Ruby
> on Rails, the 10’000’000 libraries required to make something work in
> Javascript, …).
>
> Now I do think it is indeed very important to be careful not to create
> another C++, and I would hate to see Swift going that way. Despite visible
> efforts to keep it at bay, the syntax of the language does look impressive,
> and the countless blog posts on capture semantics prove that memory
> management is not as intuitive as one would think. But judging by the few
> months I’ve been subscribed to this list, I don’t feel like the community
> (or at the very least the users of this list) is heading the way of an "12
> years of experienced minimum required" behemoth.  Additional keywords and
> syntactic constructions are often considered with a lot of prudence, and
> I’m under the impression that a solid 1/2 of the threads end up discussing
> about consistency at some points.
>
> I find it very valuable to receive this great amount of suggestions, and I
> it’d be a little bit sad if everything was simply pushed-back in favour of
> conservatism. These suggestions, and following discussions, allow us to
> constantly reevaluate the consistency and ease-of-use of the language. This
> can be seen as most of the time people end up proposing extensions to
> existing types, or operator overloads.
>
> Best regards,
> Dimitri
>
> ___
> 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] Support for pure functions. Part n + 1.

2017-02-19 Thread T.J. Usiyan via swift-evolution
I'm going to update the draft with points addressed here and the twitter
conversation. There have been quite a few implications to consider pointed
out.

This feature is not 'for' the compiler as much as it is for humans writing
code, but I will address that in the update.

On Sun, Feb 19, 2017 at 3:34 PM, David Sweeris  wrote:

>
> On Feb 19, 2017, at 11:47, Michel Fortin via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>
> 7. Is it desirable that the optimizer sometime take the pure attribute to
> heart to combine multiple apparently redundant calls into a single one? Or
> is pure not intended to be usable for compiler optimizations? The ability
> to optimize will likely be affected by the answer to these question and the
> loopholes you are willing to allow.
>
>
> AFAIK, "compiler optimizations" are main point of having a keyword for
> pure functions. (Well, that and whatever role it might play in supporting
> constant expressions, but that seems like more of a compiler implementation
> detail than an actual "feature" of pure functions.)
>
> Calling fatalError() is fine IMHO because, at that point, any side-effects
> become a moot point.
>
> I'm inclined to say that passing in reference values is ok, as long as we
> can prove the function doesn't modify anything. Don't know how we'd do
> that, though, since classes don't need that `mutating` keyword for
> functions that mutate `self`.
>
> If someone is determined to use pointers to pointers to get global state
> or something to trick the compiler into accepting *semantically* impure
> code as *syntactically* pure, I'm not sure there's a way we can really
> stop them. Not and still have @pure be useful. (Or maybe we can... I'm
> merely thinking of the saying, "every time someone builds a fool-proof
> system, the world makes a bigger fool".)
>
> I would think that allocating memory is ok, as long as it's either
> deallocated by the time the function exits or it's part of the return
> value, but I don't know a lot about low-level implementation details, so
> maybe there's something I'm missing. If that is a problem, though, I think
> the answer to your "what subset..." question would, more or less, be
> whatever subset doesn't rely on the runtime (the usefulness of that subset
> should expand if/when we extend the syntax around tuples or support
> fixed-length arrays in some other way).
>
> In any case, yeah, IMHO you're correct that we should nail down the
> semantics before worrying so much about the syntax.
>
> - Dave Sweeris
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Refactor Metatypes

2017-02-19 Thread Adrian Zubarev via swift-evolution
We added a note to the proposal:

Both Type and AnyType will be declared in the Swift standard library even 
if part of the implementation might be compiler magic. That move is really 
important to allow developers to created custom nested types named as Type. 
ModuleName.TypeName.Type is ambigious today, but will become possible after 
this proposal. That means Type and AnyType will be shortcuts for 
Swift.Type and Swift.AnyType.
We also think that the proposal is ready for the review. :)



-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 09:40:19, Adrian Zubarev 
(adrian.zuba...@devandartist.com) schrieb:

Actually Brent has just now convinced me that Metatype would be a bad name to 
choose. So forget what I said in my last messages.



-- 
Adrian Zubarev
Sent with Airmail

Am 18. Februar 2017 um 17:55:33, Adrian Zubarev 
(adrian.zuba...@devandartist.com) schrieb:

The problem I was describing is about nested types named .Type, indeed. 
Assuming the proposal would go with Type, then it means you _might_ be able 
to create nested types called Type, but you always would need to call if 
through the whole namespace (e.g. A.B.Type). That is a huge downside.

Metatype on the other hand describes exactly what that _thing_ really is.

Currently on a different branch I added this important note to the 
alternatives, but I’d rather use these types for the whole proposal.

Assuming that the accepted proposal decides to use Metatype, AnyMetatype 
over Type and AnyType would imply that the type Type would no longer be 
ambiguous to use in custome modules. However, such naming choice will affect 
the type(of:) function. It might be necessary to align the function name to 
metatype(of:) to avoid any confusion, which will result in another breaking 
change. Alternatively we could leave the function as func type(of instance: 
T) -> AnyMetatype.
If we’re going for breaking changes again than I’d prefer to align the magical 
type(of:) function to metatype(of:).

I’d love to hear more input on this.



-- 
Adrian Zubarev
Sent with Airmail

Am 18. Februar 2017 um 17:00:27, Anton Zhilin (antonyzhi...@gmail.com) schrieb:


Type is a bad name for a public type:  
FooType is almost always a better name. Libraries that describe “just types”, 
Swift types, can as well use  
Metatype or  
Mirror or something.
For nested types, like  
Foo.Type, in the meaning of “type of  
Foo“,  
Type can’t be used even now.
I’d give up on  
Type name for the greater future of metatypes.

2017-02-18 16:28 GMT+03:00 Adrian Zubarev :

Personally I’d prefer Metatype and AnyMetatype to get rid of the 
restriction where you mostly cannot create custom types called Type, which 
annoys me a lot. Sometimes Kind as a good workaround but there are times where 
Kind doesn’t fit. :/

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


Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread David Sweeris via swift-evolution

> On Feb 19, 2017, at 11:47, Michel Fortin via swift-evolution 
>  wrote:
> 
> 7. Is it desirable that the optimizer sometime take the pure attribute to 
> heart to combine multiple apparently redundant calls into a single one? Or is 
> pure not intended to be usable for compiler optimizations? The ability to 
> optimize will likely be affected by the answer to these question and the 
> loopholes you are willing to allow.

AFAIK, "compiler optimizations" are main point of having a keyword for pure 
functions. (Well, that and whatever role it might play in supporting constant 
expressions, but that seems like more of a compiler implementation detail than 
an actual "feature" of pure functions.)

Calling fatalError() is fine IMHO because, at that point, any side-effects 
become a moot point.

I'm inclined to say that passing in reference values is ok, as long as we can 
prove the function doesn't modify anything. Don't know how we'd do that, 
though, since classes don't need that `mutating` keyword for functions that 
mutate `self`.

If someone is determined to use pointers to pointers to get global state or 
something to trick the compiler into accepting semantically impure code as 
syntactically pure, I'm not sure there's a way we can really stop them. Not and 
still have @pure be useful. (Or maybe we can... I'm merely thinking of the 
saying, "every time someone builds a fool-proof system, the world makes a 
bigger fool".)

I would think that allocating memory is ok, as long as it's either deallocated 
by the time the function exits or it's part of the return value, but I don't 
know a lot about low-level implementation details, so maybe there's something 
I'm missing. If that is a problem, though, I think the answer to your "what 
subset..." question would, more or less, be whatever subset doesn't rely on the 
runtime (the usefulness of that subset should expand if/when we extend the 
syntax around tuples or support fixed-length arrays in some other way).

In any case, yeah, IMHO you're correct that we should nail down the semantics 
before worrying so much about the syntax.

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


Re: [swift-evolution] A concern

2017-02-19 Thread Dimitri Racordon via swift-evolution
Very interesting topic!

I disagree with the premise. Without having written a single line of 
Objective-C (nor Cocoa), I was able to get started with Swift in maybe 2 busy 
nights. Advanced concepts are difficult to master, but imho the learning curve 
is not that steep.

There are experts in every languages used in the industry, because actual 
production-ready applications often required experts. That is not to say that 
all languages are born equal, but my belief is that if the complexity isn’t in 
the language, then it’s somehow pushed into the libraries. In that case, being 
an expert isn’t really about mastering the language, but rather about mastering 
all the intricacies of its mainstream libraries (J2EE, Ruby on Rails, the 
10’000’000 libraries required to make something work in Javascript, …).

Now I do think it is indeed very important to be careful not to create another 
C++, and I would hate to see Swift going that way. Despite visible efforts to 
keep it at bay, the syntax of the language does look impressive, and the 
countless blog posts on capture semantics prove that memory management is not 
as intuitive as one would think. But judging by the few months I’ve been 
subscribed to this list, I don’t feel like the community (or at the very least 
the users of this list) is heading the way of an "12 years of experienced 
minimum required" behemoth.  Additional keywords and syntactic constructions 
are often considered with a lot of prudence, and I’m under the impression that 
a solid 1/2 of the threads end up discussing about consistency at some points.

I find it very valuable to receive this great amount of suggestions, and I it’d 
be a little bit sad if everything was simply pushed-back in favour of 
conservatism. These suggestions, and following discussions, allow us to 
constantly reevaluate the consistency and ease-of-use of the language. This can 
be seen as most of the time people end up proposing extensions to existing 
types, or operator overloads.

Best regards,
Dimitri

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


Re: [swift-evolution] [Proposal] Typed throws

2017-02-19 Thread Matthew Johnson via swift-evolution

> On Feb 19, 2017, at 2:16 PM, Anton Zhilin  wrote:
> 
> 2017-02-19 22:59 GMT+03:00 Matthew Johnson  >:
> 
> 
> 
>> On Feb 19, 2017, at 1:32 PM, Anton Zhilin > > wrote:
>> 
>> Now that I think about it, generic throws does not exactly cover rethrows.
>> Firstly, rethrows has semantic information that function itself does not 
>> throw—it would be lost.
>> 
> Can you elaborate further on what you mean by this?
> 
> 
> protocol Default { init() }
> 
> func exec(f: () throws -> Void) rethrows
> {
> try f()
> throw MyError()  // error because of rethrows
> }
> 
> func exec(f: () throws(E) -> Void) throws(E)
>  where E: Error & Default
> {
> try f()
> throw E()  // okay
> }

Thanks.  There is nothing wrong with this at all.  Your second `exec` would not 
accept a non-throwing function because `Never` cannot conform to `Default`.  If 
it didn’t include the `Default` constraint it would not be able to `throw E()`. 
 

If you remove the `Default` constraint and change `throws(E)` to `throws`, and 
throw `MyError()` in place of `E()` in both places then it behaves exactly as 
the first example. We don’t lose any expressivity at all.

This is actually an example of a strength of Joe’s suggestion: the second 
`exec` is able to throw an error of a type that matches the error that might be 
thrown by the calling argument `f`.  I’m not sure of where this might be useful 
but it is definitely not possible with `rethrows` while it is possible with 
Joe’s proposal.  We have more flexibility in API design under Joe’s proposal.

You did make a great point about coalescing error types from several different 
function arguments.  That’s an edge case, but the inability to coalesce is 
indeed a problem that probably needs to be addressed by the typed throws 
proposal in one way or another (if we don’t go with Joe’s suggestion we would 
need to specify how `rethrows` behaves in cases like this in some detail).


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


Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread Matthew Johnson via swift-evolution

> On Feb 19, 2017, at 1:47 PM, Michel Fortin via swift-evolution 
>  wrote:
> 
> I'm a bit disappointed to see this discussion bikeshedding the syntax without 
> clarifying much the semantics. Here's a few question of semantic nature.

+1.  I think the syntactic questions are important mostly because we need an 
answer that works for something as lightweight as a single expression closure 
without sacrificing the syntactic concision.  But the semantic questions are 
far more important and complex.

> 
> The base principle of a pure function is that it has no side effects. But 
> it's quite clear that at least some side effects will need to be allowed. So 
> which ones?
> 
> 1. Many basic calculations will leave flags in registers that persist until 
> the next computation. Those can be checked by the program later (after the 
> function is run in some cases). That's probably a side effect you want to 
> ignore.
> 
> 2. Floating point operations can give different results depending on flags 
> you can set in the registers. Things like setting the rounding mode for 
> instance. Will the pure function need to reset those flags before performing 
> floating point operations so it can guaranty the same result every time? What 
> are the implication if those are ignored?
> 
> 3. Is a pure function allowed to dereference pointers or object references 
> passed as parameters? A pointer or an object reference might provide access 
> to the global state of the program.

The answer I’ve seen thus far is yes, but only if the state that is referenced 
is constant after initialization or the access is marked with some kind of 
“trust me” annotation.

> 
> 4. Allocating memory requires access to the global memory layout of the 
> program. And allocating will give you a different memory address every time. 
> Are you allowed to allocate memory in a pure function?

I think we have to allow this (i.e. to lazily initialize a memorization cache) 
but it should probably require the “trust me” annotation.

> 
> 5. Many basic operations in the language will implicitly allocate memory or 
> dereference pointers. Same for the containers in the standard library. If you 
> don't allow memory allocations or pointer dereferencing, what subset of the 
> language is still usable in a pure function?

This feels the same as #4.  There will be parts of the standard library that 
use the “trust me” annotation and are therefore considered pure at the point of 
use despite doing these things. 

> 
> 6. If you do allow memory allocations inside the function, is it safe to 
> instantiate and return a new class? 

This is an interesting question.  If the instance is immutable my instinct is 
yes, at least in many cases (immutable classes can have value semantics).  If 
not, probably not?

> 
> 7. Is it desirable that the optimizer sometime take the pure attribute to 
> heart to combine multiple apparently redundant calls into a single one? Or is 
> pure not intended to be usable for compiler optimizations? The ability to 
> optimize will likely be affected by the answer to these question and the 
> loopholes you are willing to allow.

I think the answer has to be yes.  If it isn’t, what kind of purity do we 
really have?

This seems like a very good criteria to keep in mind in answering all of these 
questions.

> 
> 8. Is exiting the program (`fatalError`, etc.) allowed? That's a pretty big 
> side effect. Although it could also be considered as no side effect since the 
> program cannot go further.

Good question.  Does a pure function have to be total?  Allowing `fatalError` 
in a pure function is kind of like allowing it to be partial.  Some inputs 
crash rather than produce a result.  I would like to say no, but I think the 
engineering tradeoffs already made in Swift require us to say yes.  If not, you 
couldn’t do anything that might cause the language or library to trap (array 
subscript for example).

> 
> 9. Is throwing allowed? Maybe the thrown error should considered simply as 
> different return value.

Yes, throwing should be allowed as long as the same error is always thrown for 
the same input.  Consider Joe Groff’s recent suggestion for typed error 
handling.  Under that proposal *every* function can be thought of as returning 
a `Result`.  The error type for non-throwing functions is `Never` and for 
untyped throwing functions it is `Error`.  Throwing is implemented differently 
than a `Result` return type is conceptually similar.

> 
> 10. Is += allowed inside a pure function? Operators are functions too, but 
> can += be made pure with `inout` and no return value?

Local mutation should be allowed.  Mutation that can affect external state 
should not.  This is one of the really great aspects of the value semantics 
approach to values as opposed to the immutable / pure functional approach to 
values.

> 
> 11. Can you use a BigInt implementation in a pure function? BigInt needs to 
> allocate internally.

Yes.  It is pure in 

Re: [swift-evolution] [Proposal] Typed throws

2017-02-19 Thread Anton Zhilin via swift-evolution
2017-02-19 22:59 GMT+03:00 Matthew Johnson :

On Feb 19, 2017, at 1:32 PM, Anton Zhilin  wrote:
>
> Now that I think about it, generic throws does not exactly cover rethrows.
> Firstly, rethrows has semantic information that function itself does not
> throw—it would be lost.
>
> Can you elaborate further on what you mean by this?
>
protocol Default { init() }

func exec(f: () throws -> Void) rethrows
{
try f()
throw MyError()  // error because of rethrows
}

func exec(f: () throws(E) -> Void) throws(E)
 where E: Error & Default
{
try f()
throw E()  // okay
}

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


Re: [swift-evolution] [Pitch] Typed throws

2017-02-19 Thread Anton Zhilin via swift-evolution
It’s expected that if you need resilience, then you will throw an “open”
enum. Essentially, we pass resilience of typed throws on to those who will
hopefully establish resilience of enums.

If you prefer separate error types, then declare a base protocol for all
your error types and throw a protocol existential. You won’t even need
default case in switches, if closed protocols make it into the language.

I don’t like any solution that is based on comments. I think that compiler
should always ignore comments.

2017-02-18 18:27 GMT+03:00 Karl Wagner :


> So, I’m not sure about what was decided last time, but my issues with this
> are:
>
> - The thrown error type will become part of the ABI of the function. If
> you change the type of Error that is thrown, callers may not catch it. At
> the same time, if we make enums resilient by default and only allow
> specifying a single entire type, you will basically need one Error enum per
> function and it will need to be @fixed if you actually want to remove the
> catch-all block. Otherwise:
>
> // Let’s say this isn’t @fixed...
>
> enum CanFailError {
> errorOne
> errorTwo
> }
>
> func canFail() throws(CanFailError) { /* … */ }
>
> do { try canFail() }
> catch CanFailError {
> switch error {
> case .errorOne: /* handle error one */
> case .errorTwo: /* handle error two */
> default:/* handle possible new errors in later versions of
> the library */
> }
> }
>
> do { try canFail() }
> catch .errorOne { /* handle error one */ }
> catch .errorTwo { /* handle error two */  }
> catch   { /* handle possible new errors in later versions of the
> library */ }
>
> - I usually have _semantic_ namespaces for Errors, rather than single
> types per implementation pattern. If we are adding strong annotations about
> which errors can be thrown, I’d quite like to incorporate that pattern. For
> example:
>
> extension File {
>
> @fixed enum OpeningError {
>
> case .invalidPath
> case .accessDenied  // e.g. asking for write permissions for read-only file
>
> }
> @fixed enum ReadError {
>
> case .invalidOffset // past EOF
> case .deviceError   // probably worth aborting the entire operation the
> read is part of
>
> }
>
> // - throws:
> // - .OpeningError if the file can’t be opened
> // - .ReadError if the read operation fails
> func read(from offset: Int, into buffer: UnsafeBufferPointer)
> throws(OpeningError, ReadError) { /* … */ }
>
> }
>
>
> - I wonder if we could try something more ambitious. Since the list of
> thrown errors is resilience-breaking for the function, it is only
> beneficial for versioned and @inlineable functions. They should not be able
> to add new errors (they can remove them though, since errors are intended
> to be switched over). I wonder if we couldn’t introduce a small pattern
> grammar for our structured comments (isolated from the rest of the
> language) - it would be optional, but if you do list your errors, the
> compiler would validate that you do it exhaustively. Some patterns I would
> like are:
>
> // - throws: - MyError.{errorOne, errorThree, errorFive}: Something bad
>|| considered exhaustive
> @inlineable public func canFail() throws {}
>
> // - throws: - OpeningError: Computer says no... || considered
> exhaustive if OpeningError is versioned or @fixed
> //   - * || other errors,
> requires “catch-all” by external callers
> @inlineable public func canFail2() throws {}
>
> If we want to get really clever, we can have the compiler automatically
> generate those error-lists for internal functions, so you would
> automatically get exhaustive error-handling within your own module.
>
> - Karl
>
​
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Typed throws

2017-02-19 Thread Matthew Johnson via swift-evolution

> On Feb 19, 2017, at 1:32 PM, Anton Zhilin  wrote:
> 
> Now that I think about it, generic throws does not exactly cover rethrows.
> Firstly, rethrows has semantic information that function itself does not 
> throw—it would be lost.
> 
Can you elaborate further on what you mean by this?

> Secondly, rethrows allows a function with multiple throwing function 
> parameters to become non-throwing iff all the arguments are non-throwing.
> How would you express it with generics?
> In the proposal, in this case you are required to provide a non-generic 
> supertype of all used error types. This type can’t just turn into Never 
> automatically.
> 
This is a very good question.  I’m curious if Joe has a solution that doesn’t 
require introducing any additional features into Swift.

The answer I would like to see (that won’t happen in Swift 4) is to adopt some 
of the ideas in my value subtyping manifesto, including structural unions (that 
*do not* expose any members, even if there are members that all types have in 
common).  All you would be able to do with such a union is convert from one of 
its constituent types to the union type and cast back down to one of the 
constituent types.

Having unions like that would very elegantly solve the problem of a function 
that needs to throw more than one type.  It also covers the case you bring up: 
`Never | Never | Never` would be the exact same type as `Never`.  You would 
never write out `Never | Never | Never` of course, but in a generic context 
it’s important that we be able to spell it that way and have it collapse to a 
simple unordered set of its constituent types.

Use of these structural union types would be discouraged in most cases, but 
they would be very powerful and useful in specialized contexts.  Error handling 
is one of those contexts.  Another is at the boundary of a system when you need 
to accept a heterogenous collection of a small, fixed set of types (as is 
discussed in the thread about open and public protocols).

> One solution would be to retain rethrows as an additional attribute.
> It would help with semantic information, and resulting error will be able to 
> turn into Never as a special case—now that we know, that this function 
> doesn’t throw that error itself.
> 
I'm curious to hear Joe’s thought on this.  It’s possible this would be a 
necessary bridge solution until we have something more permanent as I described 
above.

> 2017-02-19 0:16 GMT+03:00 Martin Waitz  >:
> 
> 
> 
> 
>> Am 18.02.2017 um 17:37 schrieb Matthew Johnson via swift-evolution 
>> mailto:swift-evolution@swift.org>>:
>> 
>> Thank you for taking the time to put this proposal together Anton!  I really 
>> want to see typed throws make it into Swift 4.  This will be a very nice 
>> feature to have.
>> 
>> I noticed that you included Joe Groff’s idea of replacing `rethrows` by 
>> making every function have an error type which is by default `Never` for 
>> non-throwing functions and `Error` for throwing functions that do not 
>> specify an error type.  
>> 
>> I want to urge you to consider updating the proposal to take this direction 
>> now rather than later.  This is a breaking change which means the longer we 
>> wait the harder it is to justify.  In fact, I think incorporating the 
>> breaking change could increase the chances of it being accepted for Swift 4. 
>>  Without that it is a purely additive change and those are not being given 
>> priority in the Swift 4 release.
> 
> Seconded.
> With typed throwing function parameters, it makes a lot of sense to be able 
> to specify the rethrown type, based on the function given as parameter.
> 
> 

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Matthew Johnson via swift-evolution

> On Feb 18, 2017, at 10:49 PM, Dave Abrahams via swift-evolution 
> mailto:swift-evolution@swift.org>> wrote:
> 
> I'm on vacation and don't have time for a full review right now, but I am 
> concerned that wild this proposal would make enums more general and uniform 
> with the rest of the language , they also would become much more awkward for 
> common use cases. I have recently been very pleased that I didn't have to 
> supply labels in switch statements where the label name would simply have 
> matched the name of the variable to be bound.  This looks needlessly verbose:
> 
>   case .valid(value: let value, resumptionPoint: let resumptionPoint):
> 
> I cannot imagine a real life use case where one would have labels in the case 
> and desire to bind associated values to variables having different names than 
> the labels.

I agree with this, but I think it’s an issue we can solve (perhaps as an 
amendment to this proposal).

First, I think Brent’s idea of introducing an argument label that can be 
distinct from the “property” name of the case is a good one.  I think we should 
do this.  It takes the parallel with function signatures even further.

Second, we should allow the “property” name to be `_`.  This would mean no 
label can be used when matching:

case valid(value _: ValueType, resumptionPoint _: PointType)

Third, I think we should also allow suers to elide the label if they either 
discard the value with `_` or bind a name that is identical to the label, so we 
might have:

// declaration:
case valid(externalCasConstructorLabel value: ValueType, 
externalCaseConstructorLabel resumptionPoint: PointType)

// match ok:
case .valid(let value, let resumptionPoint):

// error, names do not match:
case .valid(let foo, let bar):

// ok, label is used:
case .valid(value: let foo, resumptionPoint: let bar):

This follows the behavior of function signatures very closely.  The external 
label is used to provide context for the argument at the call site (of the case 
constructor).  The internal name is used to bind a name to the value that is 
used by code that works with the value.  

The only exception here is that because the usage site is distant from the case 
declaration it may wish to use a different name.  We allow that, but only if 
the “internal name” is also used in the pattern.  This preserves the ability of 
a reader of the code to see the name / meaning of the associated value as it 
was declared by the enum in addition to the name that might make more sense for 
use in the local context.

> 
> Secondly, I can't imagine a case where one would want to use the same case 
> basename and different labels. The very common use case where the types of 
> associated values completely distinguish the case and one would rather not 
> have to supply a case name at all is completely unaddressed. If my quick read 
> is not mistaken, this proposal makes it legal for cases to have different 
> complete names (including base name and labels), but doesn't make it legal to 
> have the same full name (which I would love to be "_" or missing in some 
> cases) with different associated value types. If we were truly following the 
> precedent set by function signatures, wouldn't that be possible too?

+1.  I think this makes a lot of sense.  It completes the parallel of cases 
with overloaded functions.

I think anonymous cases are a really good idea.  I discuss those quite a bit in 
the value subtyping manifesto I shared last week (I’d love to hear your 
thoughts on it if / when you have time to take a look).

How would you propose that values of anonymous cases be constructed and 
matched?  My solution is to allow them to be constructed by implicit conversion 
from the associated value type to the enum type and matched by a cast pattern.  
Is that what you have in mind?  I would *really* love to see this someday...

> 
> Sent from my moss-covered three-handled family gradunza
> 
> On Feb 17, 2017, at 5:26 PM, John McCall  > wrote:
> 
>> Hello Swift community,
>> 
>> The review of "SE-0155: Normalize Enum Case Representation" begins now and 
>> runs through next Friday, February 26th. The proposal is available here:
>>  
>> https://github.com/apple/swift-evolution/blob/master/proposals/0155-normalize-enum-case-representation.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. When replying, please try to keep the proposal link at the top of 
>> the message:
>> 
>>  Proposal link: 
>> https://github.com/apple/swift-evolution/blob/master/proposals/0155-normali

Re: [swift-evolution] [Pitch] Support for pure functions. Part n + 1.

2017-02-19 Thread Michel Fortin via swift-evolution
I'm a bit disappointed to see this discussion bikeshedding the syntax without 
clarifying much the semantics. Here's a few question of semantic nature.

The base principle of a pure function is that it has no side effects. But it's 
quite clear that at least some side effects will need to be allowed. So which 
ones?

1. Many basic calculations will leave flags in registers that persist until the 
next computation. Those can be checked by the program later (after the function 
is run in some cases). That's probably a side effect you want to ignore.

2. Floating point operations can give different results depending on flags you 
can set in the registers. Things like setting the rounding mode for instance. 
Will the pure function need to reset those flags before performing floating 
point operations so it can guaranty the same result every time? What are the 
implication if those are ignored?

3. Is a pure function allowed to dereference pointers or object references 
passed as parameters? A pointer or an object reference might provide access to 
the global state of the program.

4. Allocating memory requires access to the global memory layout of the 
program. And allocating will give you a different memory address every time. 
Are you allowed to allocate memory in a pure function?

5. Many basic operations in the language will implicitly allocate memory or 
dereference pointers. Same for the containers in the standard library. If you 
don't allow memory allocations or pointer dereferencing, what subset of the 
language is still usable in a pure function?

6. If you do allow memory allocations inside the function, is it safe to 
instantiate and return a new class? 

7. Is it desirable that the optimizer sometime take the pure attribute to heart 
to combine multiple apparently redundant calls into a single one? Or is pure 
not intended to be usable for compiler optimizations? The ability to optimize 
will likely be affected by the answer to these question and the loopholes you 
are willing to allow.

8. Is exiting the program (`fatalError`, etc.) allowed? That's a pretty big 
side effect. Although it could also be considered as no side effect since the 
program cannot go further.

9. Is throwing allowed? Maybe the thrown error should considered simply as 
different return value.

10. Is += allowed inside a pure function? Operators are functions too, but can 
+= be made pure with `inout` and no return value?

11. Can you use a BigInt implementation in a pure function? BigInt needs to 
allocate internally.

13. Say you want to keep logs of what happens in the function in order to debug 
something: is there an "unsafe" way to do IO for that purpose? Or maybe you 
want to implement `fatalError` as a pure function: is there a way to print 
something before exiting?

Basically, there is no such thing as "no side effect". You need to pick which 
side effects are acceptable and then evaluate where your picks puts you on the 
scale between too lax (and of little utility) and too restrictive (and not 
usable outside of trivial examples). It might be a good idea to make the answer 
to all those questions clear in the proposal so people have an idea of what 
they can expect pure functions to do and what guaranties they provide.


-- 
Michel Fortin
https://michelf.ca

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


Re: [swift-evolution] [Proposal] Typed throws

2017-02-19 Thread Anton Zhilin via swift-evolution
2017-02-19 0:16 GMT+03:00 Martin Waitz :
>
> Now some bike-shedding:
> I’m not really happy with the `throws(Type)` syntax, as it is too close to
> function parameters.
> Why exactly is `throws Type` ambiguous?
> The proposal mentions `Type -> Result` as potential thrown type, but
> functions cannot conform to `Error`.
>

Well, it's expected to change with one of the follow-up proposals.


> Maybe we can instruct the parser to just allow simple type names between
> `throws` and the arrow `->`.
>

The ambiguity here is not so "to compiler" as "to human". We don't want
people to spend extra time parsing the declaration.

If that is not possible, we should at least try to find some visual hints
> to separate Error type from function parameters.
>
> E.g. we could use brackets (think of: we are specialising the `throws`):
>
> func foo() throws { … }
>

 I personally prefer parentheses, because there is precedence of
parametrized attributes. I wonder what others think on angle brackets
option.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Typed throws

2017-02-19 Thread Anton Zhilin via swift-evolution
Now that I think about it, generic throws does not exactly cover rethrows.
Firstly, rethrows has semantic information that function itself does not
throw—it would be lost.

Secondly, rethrows allows a function with multiple throwing function
parameters to become non-throwing iff all the arguments are non-throwing.
How would you express it with generics?
In the proposal, in this case you are required to provide a non-generic
supertype of all used error types. This type can’t just turn into Never
automatically.

One solution would be to retain rethrows as an additional attribute.
It would help with semantic information, and resulting error will be able
to turn into Never as a special case—now that we know, that this function
doesn’t throw that error itself.

2017-02-19 0:16 GMT+03:00 Martin Waitz :


> Am 18.02.2017 um 17:37 schrieb Matthew Johnson via swift-evolution <
> swift-evolution@swift.org>:
>
> Thank you for taking the time to put this proposal together Anton!  I
> really want to see typed throws make it into Swift 4.  This will be a very
> nice feature to have.
>
> I noticed that you included Joe Groff’s idea of replacing `rethrows` by
> making every function have an error type which is by default `Never` for
> non-throwing functions and `Error` for throwing functions that do not
> specify an error type.
>
> I want to urge you to consider updating the proposal to take this
> direction now rather than later.  This is a breaking change which means the
> longer we wait the harder it is to justify.  In fact, I think incorporating
> the breaking change could increase the chances of it being accepted for
> Swift 4.  Without that it is a purely additive change and those are not
> being given priority in the Swift 4 release.
>
>
> Seconded.
> With typed throwing function parameters, it makes a lot of sense to be
> able to specify the rethrown type, based on the function given as parameter.
>
​
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] final + lazy + fileprivate modifiers

2017-02-19 Thread Jose Cheyo Jimenez via swift-evolution


> On Feb 19, 2017, at 7:16 AM, Matthew Johnson via swift-evolution 
>  wrote:
> 
> 
> 
> Sent from my iPad
> 
>> On Feb 19, 2017, at 7:55 AM, David Hart via swift-evolution 
>>  wrote:
>> 
>> 
>> 
>>> On 19 Feb 2017, at 10:20, Goffredo Marocchi via swift-evolution 
>>>  wrote:
>>> 
>>> The current private is closer to other languages than the previous one we 
>>> had which now has in fileprivate a better name.
>> 
>> It is closer, but it's not a goal for Swift to always follow conventions of 
>> other languages. It's useful sometimes. But in this case it goes directly 
>> against the philosophy of Swift's extension feature. Swift should be allowed 
>> to go against the norm when it serves the languages. And in this case, if 
>> only one private should exist, it's the file-s open one.
> 
> Yes, I think making private not work well with extensions was the "actively 
> harmful" aspect of SE-0025.  Scoped access itself is not actively harmful and 
> should not be removed, but it could be renamed so that private works the way 
> people want it to again.
> 
I think this an excellent point. In your proposal you can also mention that 
perhaps the renaming on private to mean scope private was premature since the 
primary goal was to match other languages notion on private. The issue is that 
Swift's public does not match other languages public. Should we then also 
change Swift's public to mean the established meaning of public in other 
languages? By no means! Swift is different. We agree that scope private is 
useful to some people by we believe that it is the wrong default for Swift. It 
is actively harmful in that by making it the default it forces a programmer to 
think fileprivate the moment the want to extend a type and access their private 
members. This in turn forces every programmer to have to deal with two access 
modifiers before they even make anything public. We believe this goes against 
the swift  centric feature of extensibility via extensions and the philosophy 
of "the complexity inherited in the language needs to be progressively 
disclosed". In the same way that public doesn't make classes open, private 
should not be scope private. 

This will make it possible for people to lock down in steps instead of all 
together which doesn't work with extensions.  

We need more examples to make this case. 



>> ___
>> 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] Dictionary Enhancements

2017-02-19 Thread Ole Begemann via swift-evolution

> On 17 Feb 2017, at 01:26, Ben Cohen via swift-evolution 
>  wrote:
> 
> Here is a list of commonly requested changes/enhancements to Dictionary, all 
> of which would probably be appropriate to put together into a single 
> evolution proposal:
> 
> init from/merge in a Sequence of Key/Value pairs (already raised as SE-100: 
> https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md
>  
> ).
> make the Values view collection a MutableCollection (as in this PR: 
> https://github.com/apple/swift-evolution/pull/555 
> ).
> Add a defaulting subscript get (e.g. counts[key, default: 0] += 1 or 
> grouped(key, default:[]].append(value)).
> Add a group by-like init to create a Dictionary from a sequence of V 
> and a closure (V)->K.
Out of interest, how would you implement this? Does it require a generics 
feature that's slated for Swift 4? I tried two approaches that don't compile in 
a current Swift 3.1 snapshot (and I'm getting a segfault with both examples in 
a dev snapshot from 2017-02-14):

1)

extension Dictionary {
// error: same-type constraint 'Value' == '[S.Iterator.Element]' is 
recursive
init(values: S, groupedBy: (S.Iterator.Element) -> Key)
where Value == [S.Iterator.Element] {
...
}
}
}

2)

// error: reference to generic type 'Array' requires arguments in <...>
extension Dictionary where Value == Array {
init(values: S, groupedBy: (S.Iterator.Element) -> Key)
where S.Iterator.Element == Value.Element {
...
}
}
}

___
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-19 Thread Rien via swift-evolution

> On 19 Feb 2017, at 19:14, Chris Lattner via swift-evolution 
>  wrote:
> 
> 
>> On Feb 18, 2017, at 9:59 PM, Kevin Nattinger  wrote:
>> 
>> 
>>> 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?
> 
> As Xiaodi mentioned downthread, that is not the case.  Swift 4 stage 2 has 
> specific changes that are accepted, because it has a fixed schedule and we 
> have to prioritize the most important things for the community.
> 
> The art of evolving Swift forward is to carefully pick and choose areas to 
> focus on, both because we want to ensure a coherent language, but also 
> because implementor bandwidth is limited.
> 
> Beyond that, though syntactic sugar is always motivated by strong rationale 
> and use-cases, in my opinion, it is the most dangerous kind of additive 
> feature to consider at this point of Swift’s evolution.  While these features 
> are useful, they also clearly add complexity to the language, and it is 
> difficult to gauge whether the problem being addressed will even exist in 
> Swift as the other bigger features come in (for example, a macro system).  
> These features can also make future language evolution more problematic 
> because they consume syntactic real estate in the language.
> 
> If you’re into analogies, I see features like the generics improvements, 
> ownership model, concurrency model, macro system, new frameworks, and other 
> large scale efforts as the “bricks" that make up the house of Swift.  In that 
> analogy, syntactic sugar proposals are “mortar” that fills in the cracks 
> between the bricks.  If we add too much mortar too early on, we run the risk 
> of the house of Swift being built out of mortar, or of not being able to fit 
> the bricks into the right places.  That would be very bad, given that we all 
> want the house of Swift to be strong and beautiful over the long term.
> 
> -Chris
> 

Amen!

Regards,
Rien

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





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


Re: [swift-evolution] A concern

2017-02-19 Thread Rien via swift-evolution
No, I was referring to the original Apple document that introduced Objective-C.

But actually C is a good example.

The original work by Ritchie and Kernighan was also quite limited in scope. A 
small book and could easily be learned in a WE, I think I still have it 
somewhere in my library...

Today -as you correctly point out- C has become, well, bloatware imo.

Partly because it had to grow with time (more hw architectures), but I think 
more so because of countless committee meetings…

Regards,
Rien

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





> On 19 Feb 2017, at 18:55, Chris Lattner  wrote:
> 
> 
>> On Feb 19, 2017, at 1:00 AM, Rien via swift-evolution 
>>  wrote:
>> 
>> Hello All,
>> 
>> Its Sunday, time for some reflection...
>> 
>> One of the big plusses of Objective-C was that the entire manual was just a 
>> few pages long. I have not looked it up, but IIRC the entire manual 
>> describing the language was probably less than 50 pages. Much less if you 
>> subtract the filler stuff.
> 
> Objective-C is a superset of C, and the C parts are really important in 
> practice.  Are you including the complexity of C in your measure?
> 
> -Chris

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


Re: [swift-evolution] A concern

2017-02-19 Thread Gerard Iglesias via swift-evolution
Interesting,

You are right somewhere, today following the swift evolution, mastering swift 
with the use of the new standard lib and Cocoa is time consuming, and request 
to dedicate serious resources. 

I am not sure that the complexity come from the core language itself, it become 
complexe because of the interoperability with the low layer, think about 
Unsafe*Pointer stuff. And it would be difficult to make a point versus needs 
for powerful string capabilities, concurrency, expressivity... I love the 
support for functional programming style, conditional chaining... for exemple.

For sure almost thirty years ago I was a fan of ObjC versus C++ because of the 
Complexity gap. But at this time Foundation/Appkit was made of 32 class if I 
remember correctly ;)

Interesting that we discuss about that. There is always a need to limit entropy 
in coding :) Occam razor and KISS principles are worth to keep in mind.

Gérard 

> Le 19 févr. 2017 à 10:00, Rien via swift-evolution 
>  a écrit :
> 
> Hello All,
> 
> Its Sunday, time for some reflection...
> 
> One of the big plusses of Objective-C was that the entire manual was just a 
> few pages long. I have not looked it up, but IIRC the entire manual 
> describing the language was probably less than 50 pages. Much less if you 
> subtract the filler stuff.
> 
> Now, Objective-C is -arguably- not a very ‘nice’ or aesthetically pleasing 
> language.
> 
> Swift is a huge improvement aesthetically speaking. But at the cost of a much 
> larger user manual. Right of the bat it was clear to me that in Swift some of 
> the learning curve from the framework (Cocoa) was shifted into language 
> (Swift). I.e. Swift seemed specifically targeted to the idioms we used in 
> Objective-C/Cocoa. It was one of the reasons that I took to Swift immediately.
> 
> Now that we have Swift 3, many of the original shortcomings have been filled. 
> A few remain, but imo not very many.
> 
> That brings me to my concern: Swift seems to be on course to become a 
> behemoth of a language. 
> 
> I am absolutely convinced that everybody on this list has the best of 
> intentions. We all want the very best tool available. We want Swift to become 
> a shiny many facetted jewel among the languages.
> 
> But in doing so we might -inadvertently- make Swift into a behemoth that can 
> do everything ... if you know how!
> 
> In my opinion Swift is on course to become a very complex language where one 
> needs guru status to be a mid level programmer. Beginning programmers will 
> stand no chance whatsoever to maintain an app developed by an expert. (A bit 
> like C++, another extremely powerful language - that seems to have been 
> abandoned.)
> 
> I have been on this list now for a few weeks, and I see very little push-back 
> on new suggestions. Most of the reactions are positive-constructive. IMO we 
> need more push-back. Without it behemoth status is all but guaranteed.
> 
> I don’t know about the core team, I don’t know about Apple, I don’t know 
> where they want to go.
> 
> I just want to make a plea here: Please stop Swift from becoming a behemoth.
> 
> I don’t know if the millions (?) of Swift developers not on this list agree 
> with me. I somehow think they do, after all they are not on this list! They 
> are not looking to change Swift...
> 
> Well, I just had to get that off my chest...
> 
> To close this off, I do want to take this opportunity to thank the core team 
> for their work, I truly appreciate it!
> And whatever may come, here is one happy Swift user!
> 
> Best regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl
> 
> 
> 
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0154: Provide Custom Collections for Dictionary Keys and Values

2017-02-19 Thread Scott James Remnant via swift-evolution
This proposal directly addresses one of my least favorite patterns in Swift.

It's a good improvement and I would be content with it being accepted as-is.

However I do still feel that the solution is "clunky," and that being able to 
mutate a dictionary entry via the Optional would be much cleaner code.

Sent from my iPad

> On Feb 17, 2017, at 7:12 PM, Douglas Gregor  wrote:
> 
> Hello Swift community,
> 
> The review of SE-0154 "Provide Custom Collections for Dictionary Keys and 
> Values" begins now and runs through February 22, 2017. The proposal is 
> available here:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0154-dictionary-key-and-value-collections.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. When replying, please try to keep the proposal link at the top of 
> the message:
> 
> Proposal link:
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0154-dictionary-key-and-value-collections.md
> Reply text
> 
> Other replies
> What goes into a review?
> 
> The goal of the review process is to improve the proposal under review 
> through constructive criticism and, eventually, determine the direction of 
> Swift. When writing your review, here are some questions you might want to 
> answer in your review:
> 
> What is your evaluation of the proposal?
> Is the problem being addressed significant enough to warrant a change to 
> Swift?
> Does this proposal fit well with the feel and direction of Swift?
> If you have used other languages or libraries with a similar feature, how do 
> you feel that this proposal compares to those?
> How much effort did you put into your review? A glance, a quick reading, or 
> an in-depth study?
> More information about the Swift evolution process is available at
> 
> https://github.com/apple/swift-evolution/blob/master/process.md
> Thank you,
> 
> -Doug Gregor
> 
> Review Manager
> 
> ___
> swift-evolution-announce mailing list
> swift-evolution-annou...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution-announce
___
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-19 Thread Chris Lattner via swift-evolution

> On Feb 18, 2017, at 9:59 PM, Kevin Nattinger  wrote:
> 
> 
>> On Feb 18, 2017, at 7:33 PM, Chris Lattner via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> 
>>> On Feb 17, 2017, at 12:20 AM, Adrian Zubarev via swift-evolution 
>>> mailto:swift-evolution@swift.org>> 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?

As Xiaodi mentioned downthread, that is not the case.  Swift 4 stage 2 has 
specific changes that are accepted, because it has a fixed schedule and we have 
to prioritize the most important things for the community.

The art of evolving Swift forward is to carefully pick and choose areas to 
focus on, both because we want to ensure a coherent language, but also because 
implementor bandwidth is limited.

Beyond that, though syntactic sugar is always motivated by strong rationale and 
use-cases, in my opinion, it is the most dangerous kind of additive feature to 
consider at this point of Swift’s evolution.  While these features are useful, 
they also clearly add complexity to the language, and it is difficult to gauge 
whether the problem being addressed will even exist in Swift as the other 
bigger features come in (for example, a macro system).  These features can also 
make future language evolution more problematic because they consume syntactic 
real estate in the language.

If you’re into analogies, I see features like the generics improvements, 
ownership model, concurrency model, macro system, new frameworks, and other 
large scale efforts as the “bricks" that make up the house of Swift.  In that 
analogy, syntactic sugar proposals are “mortar” that fills in the cracks 
between the bricks.  If we add too much mortar too early on, we run the risk of 
the house of Swift being built out of mortar, or of not being able to fit the 
bricks into the right places.  That would be very bad, given that we all want 
the house of Swift to be strong and beautiful over the long term.

-Chris


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


Re: [swift-evolution] [Pitch] Typed throws

2017-02-19 Thread Chris Lattner via swift-evolution

> On Feb 17, 2017, at 11:29 AM, Matthew Johnson via swift-evolution 
>  wrote:
> 
> 
>> On Feb 17, 2017, at 1:24 PM, Xiaodi Wu via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> Let's not bring bikeshedding the commonly proposed and rejected union 
>> spelling into this.
>> Typed throws would be a nice addition, assuming that the core team finds it 
>> in scope for phase 2. It seems only logical that any type can be thrown 
>> (i.e. conforms to Error) should be permitted to be listed in `throws()`.
> 
> Agree.  Typed throws should have a single thrown type.  Making it more 
> convenient to throw and catch more than one error type with typed throws 
> without having to manually create a wrapper is an orthogonal issue.  David 
> Owens convinced me of this last year when we had a thread on the topic.

+1

-Chris

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0155: Normalize Enum Case Representation

2017-02-19 Thread Daniel Duan via swift-evolution
Hi Dave,

> On Feb 18, 2017, at 8:49 PM, Dave Abrahams via swift-evolution 
>  wrote:
> 
> I'm on vacation and don't have time for a full review right now, but I am 
> concerned that wild this proposal would make enums more general and uniform 
> with the rest of the language , they also would become much more awkward for 
> common use cases. I have recently been very pleased that I didn't have to 
> supply labels in switch statements where the label name would simply have 
> matched the name of the variable to be bound.  This looks needlessly verbose:
> 
>   case .valid(value: let value, resumptionPoint: let resumptionPoint):
> 
> I cannot imagine a real life use case where one would have labels in the case 
> and desire to bind associated values to variables having different names than 
> the labels

The degraded authoring experience is a legitimate concern. Here’s my attempt to 
make it *seems* better:

1. Perhaps it’d be a good style to treat labels similar to argument labels and 
variables in patterns as argument names:

case let .value(validated: value, resumingAt: point) // or more descriptive 
variable names, depends on usage

We’ve came to expect some repetition between a argument label and its name, so 
typing a few more characters for the label in patterns shouldn’t seem totally 
bad, maybe. From a code reader's point of view, especially for those who 
haven’t seen the case declaration, more labels should be an easy win.

2. The creator of the enum dictates style at use site. When one prefers no not 
have labels, they can use comments as documentation at the declaration.

***

That being said, the idea of matching without field name appeals to me because 
I’m used to it from other languages.

> Secondly, I can't imagine a case where one would want to use the same case 
> basename and different labels. The very common use case where the types of 
> associated values completely distinguish the case and one would rather not 
> have to supply a case name at all is completely unaddressed. If my quick read 
> is not mistaken, this proposal makes it legal for cases to have different 
> complete names (including base name and labels), but doesn't make it legal to 
> have the same full name (which I would love to be "_" or missing in some 
> cases) with different associated value types. If we were truly following the 
> precedent set by function signatures, wouldn't that be possible too?
> 

Love it. I think this should be part of this proposal. (man, if you squint, 
those cases named “_" make the whole declaration look like a C union).

> Sent from my moss-covered three-handled family gradunza
> 
> On Feb 17, 2017, at 5:26 PM, John McCall  > wrote:
> 
>> Hello Swift community,
>> 
>> The review of "SE-0155: Normalize Enum Case Representation" begins now and 
>> runs through next Friday, February 26th. The proposal is available here:
>>  
>> https://github.com/apple/swift-evolution/blob/master/proposals/0155-normalize-enum-case-representation.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. When replying, please try to keep the proposal link at the top of 
>> the message:
>> 
>>  Proposal link: 
>> https://github.com/apple/swift-evolution/blob/master/proposals/0155-normalize-enum-case-representation.md
>>  
>> 
>> 
>>  Reply text
>> 
>>  Other replies
>> 
>> What goes into a review?
>> 
>> The goal of the review process is to improve the proposal under review 
>> through constructive criticism and, eventually, determine the direction of 
>> Swift. When writing your review, here are some questions you might want to 
>> answer in your review:
>> 
>>  • What is your evaluation of the proposal?
>>  • Is the problem being addressed significant enough to warrant a change 
>> to Swift?
>>  • Does this proposal fit well with the feel and direction of Swift?
>>  • If you have used other languages or libraries with a similar feature, 
>> how do you feel that this proposal compares to those?
>>  • How much effort did you put into your review? A glance, a quick 
>> reading, or an in-depth study?
>> 
>> More information about the Swift evolution process is available at 
>> https://github.com/apple/swift-evolution/blob/master/process.md 
>> 
>> 
>> Thank you,
>> 
>> John McCall
>> Review Manager
>> ___
>> swift-evolutio

Re: [swift-evolution] A concern

2017-02-19 Thread Chris Lattner via swift-evolution

> On Feb 19, 2017, at 1:00 AM, Rien via swift-evolution 
>  wrote:
> 
> Hello All,
> 
> Its Sunday, time for some reflection...
> 
> One of the big plusses of Objective-C was that the entire manual was just a 
> few pages long. I have not looked it up, but IIRC the entire manual 
> describing the language was probably less than 50 pages. Much less if you 
> subtract the filler stuff.

Objective-C is a superset of C, and the C parts are really important in 
practice.  Are you including the complexity of C in your measure?

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
That’s the whole point I was making. :) Thank you Matthew. That makes my 
example a real world example and not just some bike shedding.

-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 18:50:31, Matthew Johnson (matt...@anandabits.com) 
schrieb:



Sent from my iPad

On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
 wrote:

Just FYI, I solved this issue in my own library (which included a json jpointer 
implementation) via:

public enum SubscriptParameter {
  case string(String)
  case int(Int)
}

extension SubscriptParameter : ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    self = .int(value)
  }
}

extension SubscriptParameter : ExpressibleByStringLiteral {
  public init(stringLiteral value: String) {
    self = .string(value)
  }
  public init(extendedGraphemeClusterLiteral value: String) {
    self.init(stringLiteral: value)
  }
  public init(unicodeScalarLiteral value: String) {
    self.init(stringLiteral: value)
  }
}

extension SubscriptParameter : CustomStringConvertible {
  public var description: String {
    switch self {
    case .string(let str):
      return "\"\(str)\""
    case .int(let i):
      return String(i)
    }
  }
}

func debug(_ path:SubscriptParameter...) {
  print("path is \(path)")
}

debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]

Can you make this work with variables - not just literals - and still prevent 
users from extending the set of types and without requiring an enum case 
constructor to be used by clients?



On Feb 19, 2017, at 1:14 AM, Adrian Zubarev  
wrote:

If you haven’t followed the other thread Matthew previously opened than you 
have missed the example I showed there.

Here it is again:

public protocol SubscriptParameterType {
   
// This property was needed to prevent the client from breaking
// the library by conforming to the protocol, but I'd like to
// keep it invisible for the client, or even better prevent the
// client from conforming to the protocol.
var parameter: Document.SubscriptParameter { get }
}

extension Document {
   
public enum SubscriptParameter {
   
case string(String)
case integer(Int)
}
}

extension String : SubscriptParameterType {
   
public var parameter: Document.SubscriptParameter {
   
return .string(self)
}
}

extension Int : SubscriptParameterType {
   
public var parameter: Document.SubscriptParameter {
   
return .integer(self)
}
}

// Somewhere inside the `Document` type
public subscript(firstKey: String, parameters: SubscriptParameterType...) -> 
Value? { … }
The absence of closed protocols forced me to create a special requirement on 
that protocol to prevent the client from conforming to that protocol and 
passing instances of other types my API wouldn’t want to deal with. That 
creates unnecessary copies and I need to unpack the enum payload to find out 
which type the user passed. Instead I could simply close the protocol, wouldn’t 
need the requirement to exist and I could simply cast the type to String or Int 
when needed.

That implementation enables more safe queries of my Document type like

document["key1", intIndexInstance, stringKeyInstance, 10, "key"]

rather than 

document["key1/\(intIndexInstance)/\(stringKeyInstance)/10/key"].

Here is a list of hidden and semi-hidden protocols from the standard library 
that could be closed. Formatted version: 
https://gist.github.com/DevAndArtist/168c800d784829be536c407311953ab7

PathProtocol
/swift/stdlib/public/core/AnyHashable.swift:16  
_HasCustomAnyHashableRepresentation
/swift/stdlib/public/core/BidirectionalCollection.swift:21  
_BidirectionalIndexable
/swift/stdlib/public/core/BridgeObjectiveC.swift:19 _ObjectiveCBridgeable
/swift/stdlib/public/core/Collection.swift:20   _IndexableBase
/swift/stdlib/public/core/Collection.swift:176  _Indexable
/swift/stdlib/public/core/CompilerProtocols.swift:193   
_ExpressibleByBuiltinIntegerLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:240   
_ExpressibleByBuiltinFloatLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:283   
_ExpressibleByBuiltinBooleanLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:316   
_ExpressibleByBuiltinUnicodeScalarLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:350   
_ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:398   
_ExpressibleByBuiltinStringLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:407   
_ExpressibleByBuiltinUTF16StringLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:670   
_ExpressibleByStringInterpolation
/swift/stdlib/public/core/CompilerProtocols.swift:709   
_ExpressibleByColorLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:720   
_ExpressibleByImageLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:730   
_ExpressibleByFileReferenceLiteral
/swift/stdli

Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Feb 19, 2017, at 10:39 AM, Adrian Zubarev 
>  wrote:
> 
> Still not what I was asking about.
> 
> Module A contains a single open protocol: open protocol P { func foo() }
> Module B contains a single open class that conforms to P:
> open class B : P {
> /* what is the default access modifier here? */ func foo()
> }
> 

I believe it would be the same with or without the protocol conformance.  In 
any case, this has nothing to do with this proposal.  It does not affect open 
classes or open protocols.

> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 19. Februar 2017 um 17:35:04, Matthew Johnson (matt...@anandabits.com) 
> schrieb:
> 
>> 
>> 
>> Sent from my iPhone
>> 
>> On Feb 19, 2017, at 10:28 AM, Adrian Zubarev 
>>  wrote:
>> 
>>> I really feel I’m blind, I cannot find it. Is the access modifier of open 
>>> protocol *members* on open/public classes public by default, or open?
>>> 
>>> If open, can we downgrade it to public in an open class?
>> 
>> I didn't specifically address members of open classes but did address open 
>> classes.  This proposal does not have any impact of the visibility of 
>> members of open classes that conform to a public (nonopen) protocol, 
>> including the default.
>>> 
>>> 
>>> -- 
>>> Adrian Zubarev
>>> Sent with Airmail
>>> 
>>> Am 19. Februar 2017 um 17:16:59, Matthew Johnson (matt...@anandabits.com) 
>>> schrieb:
>>> 
 
 
 Sent from my iPhone
 
 On Feb 19, 2017, at 10:11 AM, Adrian Zubarev 
  wrote:
 
> @Matthew: Have you considered what happens with the access modifier of an 
> open protocol when an open/public class conforms to it?
> 
 
 Yes I covered this in the detailed design section of the proposal.
> // Module A
> open protocol A {
> func foo()
> }
> 
> // Module B
> open class B : A {
> (open or public) func foo() {}
> // If `open`, can we downgrade to `public`?
> // The other way around seems straightforward
> }
>>> 
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Feb 19, 2017, at 11:29 AM, David Waite via swift-evolution 
>  wrote:
> 
> Just FYI, I solved this issue in my own library (which included a json 
> jpointer implementation) via:
> 
> public enum SubscriptParameter {
>   case string(String)
>   case int(Int)
> }
> 
> extension SubscriptParameter : ExpressibleByIntegerLiteral {
>   public init(integerLiteral value: Int) {
> self = .int(value)
>   }
> }
> 
> extension SubscriptParameter : ExpressibleByStringLiteral {
>   public init(stringLiteral value: String) {
> self = .string(value)
>   }
>   public init(extendedGraphemeClusterLiteral value: String) {
> self.init(stringLiteral: value)
>   }
>   public init(unicodeScalarLiteral value: String) {
> self.init(stringLiteral: value)
>   }
> }
> 
> extension SubscriptParameter : CustomStringConvertible {
>   public var description: String {
> switch self {
> case .string(let str):
>   return "\"\(str)\""
> case .int(let i):
>   return String(i)
> }
>   }
> }
> 
> func debug(_ path:SubscriptParameter...) {
>   print("path is \(path)")
> }
> 
> debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]

Can you make this work with variables - not just literals - and still prevent 
users from extending the set of types and without requiring an enum case 
constructor to be used by clients?


> 
>> On Feb 19, 2017, at 1:14 AM, Adrian Zubarev 
>>  wrote:
>> 
>> If you haven’t followed the other thread Matthew previously opened than you 
>> have missed the example I showed there.
>> 
>> Here it is again:
>> 
>> public protocol SubscriptParameterType {
>>   
>> // This property was needed to prevent the client from breaking
>> // the library by conforming to the protocol, but I'd like to   
>> // keep it invisible for the client, or even better prevent the
>> // client from conforming to the protocol.
>> var parameter: Document.SubscriptParameter { get }
>> }
>> 
>> extension Document {
>>   
>> public enum SubscriptParameter {
>>   
>> case string(String)
>> case integer(Int)
>> }
>> }
>> 
>> extension String : SubscriptParameterType {
>>   
>> public var parameter: Document.SubscriptParameter {
>>   
>> return .string(self)
>> }
>> }
>> 
>> extension Int : SubscriptParameterType {
>>   
>> public var parameter: Document.SubscriptParameter {
>>   
>> return .integer(self)
>> }
>> }
>> 
>> // Somewhere inside the `Document` type
>> public subscript(firstKey: String, parameters: SubscriptParameterType...) -> 
>> Value? { … }
>> The absence of closed protocols forced me to create a special requirement on 
>> that protocol to prevent the client from conforming to that protocol and 
>> passing instances of other types my API wouldn’t want to deal with. That 
>> creates unnecessary copies and I need to unpack the enum payload to find out 
>> which type the user passed. Instead I could simply close the protocol, 
>> wouldn’t need the requirement to exist and I could simply cast the type to 
>> String or Int when needed.
>> 
>> That implementation enables more safe queries of my Document type like
>> 
>> document["key1", intIndexInstance, stringKeyInstance, 10, "key"]
>> 
>> rather than 
>> 
>> document["key1/\(intIndexInstance)/\(stringKeyInstance)/10/key"].
>> 
>> Here is a list of hidden and semi-hidden protocols from the standard library 
>> that could be closed. Formatted version: 
>> https://gist.github.com/DevAndArtist/168c800d784829be536c407311953ab7
>> 
>> Path Protocol
>> /swift/stdlib/public/core/AnyHashable.swift:16   
>> _HasCustomAnyHashableRepresentation
>> /swift/stdlib/public/core/BidirectionalCollection.swift:21   
>> _BidirectionalIndexable
>> /swift/stdlib/public/core/BridgeObjectiveC.swift:19  _ObjectiveCBridgeable
>> /swift/stdlib/public/core/Collection.swift:20_IndexableBase
>> /swift/stdlib/public/core/Collection.swift:176   _Indexable
>> /swift/stdlib/public/core/CompilerProtocols.swift:193
>> _ExpressibleByBuiltinIntegerLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:240
>> _ExpressibleByBuiltinFloatLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:283
>> _ExpressibleByBuiltinBooleanLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:316
>> _ExpressibleByBuiltinUnicodeScalarLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:350
>> _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:398
>> _ExpressibleByBuiltinStringLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:407
>> _ExpressibleByBuiltinUTF16StringLiteral
>> /swift/stdlib/public/core/CompilerProtocols.swift:670
>> _ExpressibleByStringInterpolation
>> /swift/stdlib/public/core/CompilerProtocols.swift:709
>> _ExpressibleByColorLiteral
>> /swift/stdlib/public/core/CompilerPro

Re: [swift-evolution] [Pitch] Typed throws

2017-02-19 Thread Matthew Johnson via swift-evolution


Sent from my iPad

> On Feb 19, 2017, at 11:34 AM, Brandon Knope via swift-evolution 
>  wrote:
> 
> I really like this. Seems much more elegant and simple this way 

+1

> 
>> On Feb 17, 2017, at 4:45 PM, Joe Groff via swift-evolution 
>>  wrote:
>> 
>> 
>>> 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
>> Do you actually need that? Experience in other languages like Rust and 
>> Haskell that use Result-based error propagation suggests that a single error 
>> type is adequate, and beneficial in many ways. If nothing else, you could 
>> `Either` your way to multiple errors if you really needed to.
>> 
>> IMO, if we accept a single error type per function, there could be a simpler 
>> model for this. We could say that the `throws` type is a generic parameter 
>> of all function types, and it defaults to the uninhabited `Never` type for 
>> functions that don't throw.
>> 
>> () -> () == () throws Never -> ()
>> () throws -> () == () throws Error -> ()
>> 
>> In this model, you'd get many benefits:
>> 
>> - `rethrows` could become first-class, reducing down to just polymorphic 
>> `throws`:
>> 
>> func foo(_: () throws -> ()) rethrows // Swift 3
>> func foo(_: () throws T -> ()) throws T // Swift X
>> func foo(_: () throws T -> ()) throws Either
>> 
>> - Protocols could abstract over error handling; for instance, we could 
>> support throwing sequences:
>> 
>> protocol IteratorProtocol {
>>   associatedtype Element
>>   associatedtype Error: Swift.Error = Never
>> 
>>   mutating func next() throws Error -> Element?
>> }
>> 
>> Separate of the type system model, the type *checking* model also deserves 
>> thorough consideration. Propagating the effects of possibly multiple error 
>> types propagating within a `do` block is much trickier than doing so as a 
>> single "throws" or not bit, especially if you want to be able to use type 
>> context in `catch` patterns or to implicitly propagate a narrower `throws` 
>> type out of the enclosing function.
>> 
>> -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] [Draft] open and public protocols

2017-02-19 Thread Karl Wagner via swift-evolution

> On 19 Feb 2017, at 17:36, David Hart  wrote:
> 
> This makes more sense already. But in this case, wouldn't I be interested, as 
> a client, in creating my own TextStreams, some of which might write to a 
> custom log file, to a web service, etc... ?
> 
> On 19 Feb 2017, at 17:00, Karl Wagner  > wrote:
> 
>> 
>>> On 19 Feb 2017, at 16:17, David Hart via swift-evolution 
>>> mailto:swift-evolution@swift.org>> wrote:
>>> 
>>> I still don't see the use case for this. Perhaps I'm wrong, but if an API 
>>> creates a protocol for the sole purpose of representing a set of concrete 
>>> types, that looks more to me like bad API design, and not a missing feature 
>>> in the language. Can you give me a small concrete real-world example of an 
>>> API which requires that? 
>> 
>> 
>> Whether or not a protocol is open is also a part of API expressivity; often 
>> a library will want to expose a protocol only as a way to enable 
>> generic/existential programming over a fixed set of types, without intending 
>> that any clients add new conformers. Protocols are crucial to expressing the 
>> shared patterns amongst the set of types.
>> 
>> For example, I might have a TextStream protocol:
>> 
>> public protocol TextStream {
>> func write(_: String)
>> }
>> 
>> And I might decide to expose a property as type “TextStream” purely because 
>> I reserve the right to change the underlying concrete type. I want clients 
>> to work on the protocol-existential level.
>> 
>> public class Component {
>> var debugWriter: TextStream
>> }
>> 
>> By doing that, the underlying concrete type is no longer part of my API or 
>> ABI. I can change it between versions without breaking clients, but it’s not 
>> meaningful for any clients to create their own TextStreams; that’s not part 
>> of what my library does/allows.
>> 
>> - Karl

Perhaps, but there are times when you don’t want that, or when accommodating 
custom instances is not so straightforward. The debugWriter instance is only 
_exposed_ as a “TextStream”; but there may be more (internal) requirements on 
the underlying instance - e.g. that it is Flushable, 
InitialisableFromNativeFileObject, or whatever. I would rather not expose them 
all, and just expose the instance as “something which is a TextStream, so you 
can call TextStream methods on it”, if I decide that’s all they need to know.

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


Re: [swift-evolution] [Draft] open and public protocols

2017-02-19 Thread Adrian Zubarev via swift-evolution
Try to pass let intInstance = 42 in your function. ;)

That will result in .int(intInstance).

My implementation does not need that at all.



-- 
Adrian Zubarev
Sent with Airmail

Am 19. Februar 2017 um 18:29:54, David Waite (da...@alkaline-solutions.com) 
schrieb:

Just FYI, I solved this issue in my own library (which included a json jpointer 
implementation) via:

public enum SubscriptParameter {
  case string(String)
  case int(Int)
}

extension SubscriptParameter : ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    self = .int(value)
  }
}

extension SubscriptParameter : ExpressibleByStringLiteral {
  public init(stringLiteral value: String) {
    self = .string(value)
  }
  public init(extendedGraphemeClusterLiteral value: String) {
    self.init(stringLiteral: value)
  }
  public init(unicodeScalarLiteral value: String) {
    self.init(stringLiteral: value)
  }
}

extension SubscriptParameter : CustomStringConvertible {
  public var description: String {
    switch self {
    case .string(let str):
      return "\"\(str)\""
    case .int(let i):
      return String(i)
    }
  }
}

func debug(_ path:SubscriptParameter...) {
  print("path is \(path)")
}

debug(1, "foo", 2, "bar”) // path is [1, “foo”, 2, “bar”]

On Feb 19, 2017, at 1:14 AM, Adrian Zubarev  
wrote:

If you haven’t followed the other thread Matthew previously opened than you 
have missed the example I showed there.

Here it is again:

public protocol SubscriptParameterType {
   
// This property was needed to prevent the client from breaking
// the library by conforming to the protocol, but I'd like to
// keep it invisible for the client, or even better prevent the
// client from conforming to the protocol.
var parameter: Document.SubscriptParameter { get }
}

extension Document {
   
public enum SubscriptParameter {
   
case string(String)
case integer(Int)
}
}

extension String : SubscriptParameterType {
   
public var parameter: Document.SubscriptParameter {
   
return .string(self)
}
}

extension Int : SubscriptParameterType {
   
public var parameter: Document.SubscriptParameter {
   
return .integer(self)
}
}

// Somewhere inside the `Document` type
public subscript(firstKey: String, parameters: SubscriptParameterType...) -> 
Value? { … }
The absence of closed protocols forced me to create a special requirement on 
that protocol to prevent the client from conforming to that protocol and 
passing instances of other types my API wouldn’t want to deal with. That 
creates unnecessary copies and I need to unpack the enum payload to find out 
which type the user passed. Instead I could simply close the protocol, wouldn’t 
need the requirement to exist and I could simply cast the type to String or Int 
when needed.

That implementation enables more safe queries of my Document type like

document["key1", intIndexInstance, stringKeyInstance, 10, "key"]

rather than 

document["key1/\(intIndexInstance)/\(stringKeyInstance)/10/key"].

Here is a list of hidden and semi-hidden protocols from the standard library 
that could be closed. Formatted version: 
https://gist.github.com/DevAndArtist/168c800d784829be536c407311953ab7

PathProtocol
/swift/stdlib/public/core/AnyHashable.swift:16  
_HasCustomAnyHashableRepresentation
/swift/stdlib/public/core/BidirectionalCollection.swift:21  
_BidirectionalIndexable
/swift/stdlib/public/core/BridgeObjectiveC.swift:19 _ObjectiveCBridgeable
/swift/stdlib/public/core/Collection.swift:20   _IndexableBase
/swift/stdlib/public/core/Collection.swift:176  _Indexable
/swift/stdlib/public/core/CompilerProtocols.swift:193   
_ExpressibleByBuiltinIntegerLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:240   
_ExpressibleByBuiltinFloatLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:283   
_ExpressibleByBuiltinBooleanLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:316   
_ExpressibleByBuiltinUnicodeScalarLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:350   
_ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:398   
_ExpressibleByBuiltinStringLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:407   
_ExpressibleByBuiltinUTF16StringLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:670   
_ExpressibleByStringInterpolation
/swift/stdlib/public/core/CompilerProtocols.swift:709   
_ExpressibleByColorLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:720   
_ExpressibleByImageLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:730   
_ExpressibleByFileReferenceLiteral
/swift/stdlib/public/core/CompilerProtocols.swift:750   _DestructorSafeContainer
/swift/stdlib/public/core/FixedPoint.swift.gyb:53   _Integer
/swift/stdlib/public/core/FixedPoint.swift.gyb:70   _SignedInteger
/swift/stdlib/public/core/FixedPoint.swift.gyb:108  
_DisallowMixed

  1   2   >