Re: [swift-evolution] Int indexing into UTF16View

2017-06-10 Thread Charles Srstka via swift-evolution
> On Jun 8, 2017, at 2:35 PM, Tony Allevato via swift-evolution 
>  wrote:
> 
> It is an extremely rare case for a developer to know a priori what literal 
> numeric indices should be used when indexing into a string, because it only 
> applies when strings fall into a very specific format and encoding.

Knowing this is required for accessibility support on macOS, since it’s needed 
to implement NSAccessibility methods such as 
accessibilityAttributedString(for:), accessibilityRTF(for:), 
accessibilityFrame(for:), etc.

Charles

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


Re: [swift-evolution] Int indexing into UTF16View

2017-06-10 Thread Ben Cohen via swift-evolution

> On Jun 8, 2017, at 10:32 AM, David Hart via swift-evolution 
>  wrote:
> 
> Hello,
> 
> When working with Strings which are known to be ASCII, I tend to use the 
> UTF16View for the performance of random access. I would also like to have the 
> convenience of indexing with Int:
> 
> let barcode = "M1X/CLEMENT   EELT9QBQGVAAMSEZY1353 244 21D 531  
> 10A1311446838”
> let name = barcode.utf16[2..<22]
> let pnrCode = barcode.utf16[23..<30]
> let seatNo = barcode.utf16[47..<51]
> let fromCity = barcode.utf16[30..<33]
> let toCity = barcode.utf16[33..<36]
> let carrier = barcode.utf16[36..<39]
> let flightNumber = barcode.utf16[39..<44]
> let day = barcode.utf16[44..<47]
> 
> I define my own subscript in an extension to UTF16View but I think this 
> should go in the Standard Library.
> Any thoughts?
> 
> David.
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


Hi David,

My view is positional shredding of strings is enough of a use case that we 
ought to think about handling it better. I don’t think having to convert the 
string into an Array of Character, or bytes, or use Data, should be necessary, 
since this implies losing the stringiness of the slices you are creating, which 
is an inconvenience for many use cases. Strings-as-data is a thing we should 
support, and support well.

But I also don’t think giving String or its views integer indices is the right 
way to go either, incorrectly implying as it does random access 

(or, even if we did end up making utf16 permanently random-access, encouraging 
people towards using utf16 to support this use case when often they’d be better 
served sticking with characters).

There’s a few things to note about the example you give:
1) Do you really want utf16 view slices for your variable types? Maybe in this 
case you do, but I would guess a lot of the time what is desired would be a 
(sub)string.
2) Do you really want to hard-code integer literals into your code? Maybe for a 
quick shell script use case, but for anything more this seems like an 
anti-pattern that integer indices encourage.
3) Are you likely to actually want validation at each step – that the string 
was long enough, that the string data was valid at that point?
4) This case doesn’t seem to need random access particularly, so much as the 
(questionable? see above) convenience of integer indexing. Although reordered 
in the example, it seems like the code could be written to progressively 
traverse the string from left to right to get the fields. Unless the plan is to 
repeatedly access some fields over and over. But I’m not sure we’d want to put 
affordances into the std lib to encourage accessing stringly typed data...

So the question is, what affordances should we put into the standard library, 
or maybe other libraries, to help with these use cases? This is a big design 
space to explore, and at least some ideas ought to feed into our ongoing 
improvements to String for future releases.

For example:

Now that we have Substring, it opens up the ability to efficiently consume from 
the front (since it’s just adjusting the substring range):

extension Collection where Self == SubSequence {
// or some better name...
mutating func removeFirst(_ n: IndexDistance) -> SubSequence? {
guard let i = index(startIndex, offsetBy: n, limitedBy: endIndex)
else { return nil }

defer { self = self[i...] }
return self[.. [String:SubSequence]? // or 
throw an error with a field name
where P.Element == (key: String, value: CountableRange)
}

let barcodeSchema: DictionaryLiteral = [
"name": 2..<22,
"pnrCode": 23..<30,
"fromCity": 30..<33,
"toCity": 33..<36,
"carrier": 36..<39,
"flightNumber": 39..<44,
"day": 45..<47,
"seatNo": 47..<51,
]

let fields = barcode.fields(at: barcodeSchema)!

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


Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Haravikk via swift-evolution

> On 10 Jun 2017, at 13:33, Xiaodi Wu via swift-evolution 
>  wrote:
> 
> _Every_ addition to the basic syntax of the language is, by definition, high 
> cost. The bar for additions to the standard library is already very high; the 
> bar for additions to control flow syntax would be extraordinarily high.
> 
> The proposed use case here is far from the original topic of repeat {} while, 
> which is unique because the condition lexically follows the loop.
> 
> For those loops in Swift where it is possible to declare variables in the 
> condition, these live in a magical middle scope that is intuitive to use but 
> also an exception to the rule of thumb that scopes are surrounded by braces. 
> As I wrote earlier, it is possible to manually create an analogous scope by 
> surrounding any loop with do {}. Any addition to the language would have to 
> be vastly superior to this currently possible alternative, and I seriously 
> doubt it is possible to invent such a thing because anything shorter than the 
> four letters in “do {}” would also obscure the existence of the middle scope 
> being created.

The problem with nesting within do {} blocks is that it actually makes the 
problem worse; the main benefit of being able to declare the variables more 
conveniently is to eliminate common boiler-plate around loops. Creating them 
with a limited scope is a useful bonus (and further reduces clutter/name 
pollution).

On the issue of tackling boilerplate, consider something like the following:

// Remove the first 100+ units of items and store the names in an array
var theNames:[String] = []
do {
var theTotal = 0
while let eachItem = theIterator.next() {
theNames.append(eachItem.name)
theTotal += eachItem.value
if theTotal >= 100 { break }
}
}

With the ability to specify throwaway variables more easily, I'm sticking with 
my using syntax here:

var theNames:[String] = []
while let eachItem = theIterator.next() using (var theTotal = 0) where 
(theTotal < 100) {
theNames.append(eachItem.name)
theTotal += eachItem.value
}

Depending upon your preference on how to structure the using and where parts 
this is shorter and easier.


In terms of purely creating throwaway variables, it could be condensed a bit 
further if we stole anonymous variables from the closure syntax like so:

var theNames:[String] = []
while let eachItem = theIterator.next() using $0 = 0 where $0 < 100 { // $0 is 
created for this block only
theNames.append(eachItem.name)
$0 += eachItem.value
}

In other words, we'd treat $0 = 0 as a shorthand for var foo = 0 on the basis 
that it's being used for a limited scope (i.e- it's always an initialisation 
within the using clause, rather than an assignment). This should be consistent 
with closures on the basis that closures have implicitly created the variables 
for you.___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
The difference between a convenience initializer and an indirect initializer is 
that convenience initializer has to initialize an existing instance, so its 
options of delegating the responsibility are limited by the guarantees that the 
initializer requires. On the other hand, an indirect initializer is pretty much 
a normal static function which doesn't need any guarantees at all, so it could 
get the instance from wherever it wanted. I can't say I'm totally sure about 
this, but it seems like limiting the overridability wouldn't server any real 
purpose.

I initially decided to include the Objective-C/C part because the current 
behavior of imported initializers exactly matches that of an indirect 
initializer, so if these changes would be made, *all* non-indirect initializers 
(both native and imported) would have static typing guarantees that could be 
exploited by the compiler. I don't think it's critical, because Swift is now at 
the brink of major version 4 and this odd imported initializer behavior hasn't 
seemed to have caused any trouble. Still, I think as a sneak peek at a future 
proposal to clean up the imported initializers would be warranted as a 
side-note in this proposal for the core team to get a better understanding of 
where this could go.

About the formulation: I'm just being overly pedantic about everything as 
usual. I just thought that the core team would prefer something more like a 
spec document, rather then a favor. It's really the least important aspect at 
this point, so it's fine 

> On Jun 11, 2017, at 1:54 AM, Riley Testut  wrote:
> 
> IIRC I had a discussion with Douglas Gregor about the overriding aspect of 
> factory initializers, and the takeaway was that it would just be like 
> convenience initializers. Technically, convenience initializers cannot be 
> overridden, but a subclass *can* implement a convenience method with the same 
> signature as its superclass' convenience method. The only difference is it 
> can't call the super initializer. I think this *does* make the most sense, 
> because I'm not sure super.init for an indirect initializer makes much sense, 
> and if you really wanted to do that, you could just call the initializer 
> directly (aka "let superReturnValue = Type()). But happy to change if you 
> feel strongly it should be allowed!
> 
> I left out the Objective-C/C interoperability aspects because IMO they aren't 
> necessary for this proposal. This proposal is specifically limited to adding 
> a new indirect initializer to Swift. I could mention that it would be exposed 
> to Objective-C just like other initializers, but anything more than that I 
> think should be a separate proposal (such as how C/Objective-C initializers 
> would be imported).
> 
> Also, what parts sound like a personal letter? The motivation + examples are 
> motivated by personal experience, and so I wrote them from my perspective 
> (similar to other proposals), but the proposed solution + detailed design 
> should be straightforward and void of opinions. 
> 
> On Jun 10, 2017, at 5:25 PM, Gor Gyolchanyan  > wrote:
> 
>> Looks good, but I have a few thoughts on it:
>> 
>> * I think indirect initializers *shoud* be overridable, but only by other 
>> indirect initializers. This will allow subclasses of the factory to expand 
>> the factory method by adding new possible instances to return.
>> * You did not include the specification of implementation details that I 
>> provided as well as C/Objective-C interoperability changes.
>> * The proposal is formulated more like a personal opinion, rather then a 
>> formal specification. It sounds like a personal letter. I'd recommend 
>> writing it similarly as you'd write a wikipedia page.
>> 
>>> On Jun 11, 2017, at 1:12 AM, Riley Testut >> > wrote:
>>> 
>>> Awesome! Updated my proposal to include what I believed to be the relevant 
>>> portions of your indirect initializer idea. Let me know if there’s anything 
>>> I missed or should change :-)
>>> 
>>> https://github.com/rileytestut/swift-evolution/blob/master/proposals/-factory-initializers.md
>>>  
>>> 
 On Jun 10, 2017, at 12:43 PM, Gor Gyolchanyan > wrote:
 
 Hi, Riley!
 
 I think that's a great idea! We can merge the second part of my proposal 
 (the `indirect init`) into your one and refine and consolidate the 
 prerequisite proposal (about returning from `init` and possibly in-place 
 member initializers) and bunch them up into a proposal cluster (the way 
 swift coders did).
 Feel free to tear out any chunks from my proposal, while I think about a 
 more in-depth rationale about revamping initialization syntax. 
 
> On Jun 10, 2017, 

Re: [swift-evolution] Type Safe Key-Value Construct

2017-06-10 Thread T.J. Usiyan via swift-evolution
Wouldn't a struct be the better answer here overall or (with slightly fewer
assurances) using an enum as the `Value` type?



On Sat, Jun 10, 2017 at 12:56 PM, David Moore via swift-evolution <
swift-evolution@swift.org> wrote:

>
> Hello swift-evolution,
>
> There are clearly weaknesses with obtaining values from a given dictionary
> in swift. Most notably, if we have a [String: Any] dictionary, how is one
> supposed to set/get a value with type safety? The following concept
> addresses this very issue.
>
> I regularly use a self-constructed structure with static constants
> embedded within it, the structure enables a type safe implementation of
> keys and values (especially Dictionary applications). I will include a code
> snippet later on in this message, but I would specifically like to describe
> the benefits of a type safe key and value system, and how it would benefit
> the language.
>
> When using dictionaries in Swift, one often finds themselves needing to
> use more general key and value types (e.g. [String: Any]). Unfortunately,
> when a Dictionary uses a general type, rather than one with more type
> safety and compile time checks, many issues can arise from such a use case.
>
> The solution, in my opinion, is to use a pairing struct which can be used
> to create constant type-safe-enforcing structures. Additionally, said
> struct could have the ability to transform values of one type to that of
> another. Please see the code snippet below for more information regarding
> the implementation.
>
> struct Bar {
>
> var str: String
>
> }
>
>
> var foo = [String: Any]()
>
> foo["bar"] = Bar(str: "Hello, world.")
>
>
> // We are optionally casting this value of `Any` to `Bar`, but it's
> strongly typed, so there are clearly drawbacks.
>
> if let bar = foo["bar"] as? Bar {
>
> bar.str
>
> }
>
>
> // What if we use a `KeyValuePair`?
>
> let barPair = KeyValuePair(key: "bar")
>
> barPair.addValue(Bar(str: "This is better."), to: )
>
>
> // Now look how easy (and safe) it is to get the value.
>
> let bar = barPair.value(from: foo)
>
>
> I have already implemented the underlying structure for the above example
> usage. Also, there are other use cases that are not highlighted here, such
> as built in value transformation.
>
> Let me know if anyone else agrees that this is a type safe solution for
> generalized dictionaries, or if think there are other uses for it. I also
> have all the code for the struct KeyValuePair, if anyone wants to see how
> it works, but it’s quite lightweight.
>
> Thank you,
>
> [image: Moore Development]
>
> David Moore / Owner / Chief Executive Officer
> da...@mooredev.ca / (705) 845-6057
>
> Moore Development
> https://www.mooredev.ca
>
> 
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Riley Testut via swift-evolution
IIRC I had a discussion with Douglas Gregor about the overriding aspect of 
factory initializers, and the takeaway was that it would just be like 
convenience initializers. Technically, convenience initializers cannot be 
overridden, but a subclass *can* implement a convenience method with the same 
signature as its superclass' convenience method. The only difference is it 
can't call the super initializer. I think this *does* make the most sense, 
because I'm not sure super.init for an indirect initializer makes much sense, 
and if you really wanted to do that, you could just call the initializer 
directly (aka "let superReturnValue = Type()). But happy to change if you feel 
strongly it should be allowed!

I left out the Objective-C/C interoperability aspects because IMO they aren't 
necessary for this proposal. This proposal is specifically limited to adding a 
new indirect initializer to Swift. I could mention that it would be exposed to 
Objective-C just like other initializers, but anything more than that I think 
should be a separate proposal (such as how C/Objective-C initializers would be 
imported).

Also, what parts sound like a personal letter? The motivation + examples are 
motivated by personal experience, and so I wrote them from my perspective 
(similar to other proposals), but the proposed solution + detailed design 
should be straightforward and void of opinions. 

> On Jun 10, 2017, at 5:25 PM, Gor Gyolchanyan  wrote:
> 
> Looks good, but I have a few thoughts on it:
> 
> * I think indirect initializers *shoud* be overridable, but only by other 
> indirect initializers. This will allow subclasses of the factory to expand 
> the factory method by adding new possible instances to return.
> * You did not include the specification of implementation details that I 
> provided as well as C/Objective-C interoperability changes.
> * The proposal is formulated more like a personal opinion, rather then a 
> formal specification. It sounds like a personal letter. I'd recommend writing 
> it similarly as you'd write a wikipedia page.
> 
>> On Jun 11, 2017, at 1:12 AM, Riley Testut  wrote:
>> 
>> Awesome! Updated my proposal to include what I believed to be the relevant 
>> portions of your indirect initializer idea. Let me know if there’s anything 
>> I missed or should change :-)
>> 
>> https://github.com/rileytestut/swift-evolution/blob/master/proposals/-factory-initializers.md
>> 
>>> On Jun 10, 2017, at 12:43 PM, Gor Gyolchanyan  wrote:
>>> 
>>> Hi, Riley!
>>> 
>>> I think that's a great idea! We can merge the second part of my proposal 
>>> (the `indirect init`) into your one and refine and consolidate the 
>>> prerequisite proposal (about returning from `init` and possibly in-place 
>>> member initializers) and bunch them up into a proposal cluster (the way 
>>> swift coders did).
>>> Feel free to tear out any chunks from my proposal, while I think about a 
>>> more in-depth rationale about revamping initialization syntax. 
>>> 
 On Jun 10, 2017, at 8:36 PM, Riley Testut  wrote:
 
 Hi Gor 
 
 I’m very much in fan of a unified initialization syntax. I submitted my 
 own proposal for factory initializers a while back, but since it wasn’t a 
 focus of Swift 3 or 4 I haven’t followed up on it recently. In the time 
 since last working on it, I came to my own conclusion that rather than 
 focusing on factory initialization, the overall initialization process 
 should be simplified, which I’m glad to see someone else has realized as 
 well :-)
 
 Here’s my proposal for reference: 
 https://github.com/apple/swift-evolution/pull/247/commits/58b5a93b322aae998eb40574dee15fe54323de2e
  Originally I used the “factory” keyword, but I think your “indirect” 
 keyword may be a better fit (since it has precedent in the language and is 
 not limited to “just” being about factory initialization). To divide your 
 proposal up into smaller pieces for review, maybe we could update my 
 proposal to use your indirect keyword, and then start a separate 
 topic/proposal for the remaining aspects of your proposal? I agree that 
 splitting it into smaller chunks may be better for the process.
 
 Let me know what you think!
 
 Riley
 
 
>> On Jun 10, 2017, at 3:33 AM, Gor Gyolchanyan via swift-evolution 
>>  wrote:
>> 
>> 
>> This is a very interesting read.
> 
> Thanks you! I tried to make it as clear and detailed as possible.  
> 
>> 
>> We did not discuss the 'indirect' idea at all on this list. Did you come 
>> up with it just now? In any case, my suggestion as to moving forward 
>> would be this:
> I was writing the proposal and was just about to write `factory init`, 
> when it occurred to me: enums already have a keyword that does 

Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Looks good, but I have a few thoughts on it:

* I think indirect initializers *shoud* be overridable, but only by other 
indirect initializers. This will allow subclasses of the factory to expand the 
factory method by adding new possible instances to return.
* You did not include the specification of implementation details that I 
provided as well as C/Objective-C interoperability changes.
* The proposal is formulated more like a personal opinion, rather then a formal 
specification. It sounds like a personal letter. I'd recommend writing it 
similarly as you'd write a wikipedia page.

> On Jun 11, 2017, at 1:12 AM, Riley Testut  wrote:
> 
> Awesome! Updated my proposal to include what I believed to be the relevant 
> portions of your indirect initializer idea. Let me know if there’s anything I 
> missed or should change :-)
> 
> https://github.com/rileytestut/swift-evolution/blob/master/proposals/-factory-initializers.md
>  
> 
>> On Jun 10, 2017, at 12:43 PM, Gor Gyolchanyan > > wrote:
>> 
>> Hi, Riley!
>> 
>> I think that's a great idea! We can merge the second part of my proposal 
>> (the `indirect init`) into your one and refine and consolidate the 
>> prerequisite proposal (about returning from `init` and possibly in-place 
>> member initializers) and bunch them up into a proposal cluster (the way 
>> swift coders did).
>> Feel free to tear out any chunks from my proposal, while I think about a 
>> more in-depth rationale about revamping initialization syntax. 
>> 
>>> On Jun 10, 2017, at 8:36 PM, Riley Testut >> > wrote:
>>> 
>>> Hi Gor 
>>> 
>>> I’m very much in fan of a unified initialization syntax. I submitted my own 
>>> proposal for factory initializers a while back, but since it wasn’t a focus 
>>> of Swift 3 or 4 I haven’t followed up on it recently. In the time since 
>>> last working on it, I came to my own conclusion that rather than focusing 
>>> on factory initialization, the overall initialization process should be 
>>> simplified, which I’m glad to see someone else has realized as well :-)
>>> 
>>> Here’s my proposal for reference: 
>>> https://github.com/apple/swift-evolution/pull/247/commits/58b5a93b322aae998eb40574dee15fe54323de2e
>>>  
>>> 
>>>  Originally I used the “factory” keyword, but I think your “indirect” 
>>> keyword may be a better fit (since it has precedent in the language and is 
>>> not limited to “just” being about factory initialization). To divide your 
>>> proposal up into smaller pieces for review, maybe we could update my 
>>> proposal to use your indirect keyword, and then start a separate 
>>> topic/proposal for the remaining aspects of your proposal? I agree that 
>>> splitting it into smaller chunks may be better for the process.
>>> 
>>> Let me know what you think!
>>> 
>>> Riley
>>> 
>>> 
 On Jun 10, 2017, at 3:33 AM, Gor Gyolchanyan via swift-evolution 
 > wrote:
 
> 
> This is a very interesting read.
> 
 
 Thanks you! I tried to make it as clear and detailed as possible.  
 
> 
> We did not discuss the 'indirect' idea at all on this list. Did you come 
> up with it just now? In any case, my suggestion as to moving forward 
> would be this:
> 
 I was writing the proposal and was just about to write `factory init`, 
 when it occurred to me: enums already have a keyword that does something 
 very similar. It seemed to me that an initializer that doesn't initialize 
 the instance in-place, but returns a completely separate instance from 
 somewhere else, is kinda "indirectly" initializing the instance. Plus, the 
 already established keyword and its semantic would reduce the learning 
 curve for this new feature and separate it from a single specific use case 
 (the "factory method" pattern).
 
> 
> - Do you feel that both halves of your draft (expanding `return` in 
> initializers, and `indirect` initializers) should absolutely be one 
> proposal, or can they be separated?
> 
 I think the `return` can be easily implemented first, while opening up an 
 opportunity to later implement `indirect init`. The reason why I unified 
 them was that the `return` idea on its own has very limited merit and 
 could the thought of as a low-priority cosmetic enhancement. I wouldn't 
 want it to be viewed that way because the primary purpose of that idea is 
 to enable `indirect init` (which Cocoa and Cocoa Touch developers would be 
 very happy about). 
 
> 
> a) If they can be separated because each half has individual merit, 

Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Riley Testut via swift-evolution
Awesome! Updated my proposal to include what I believed to be the relevant 
portions of your indirect initializer idea. Let me know if there’s anything I 
missed or should change :-)

https://github.com/rileytestut/swift-evolution/blob/master/proposals/-factory-initializers.md

> On Jun 10, 2017, at 12:43 PM, Gor Gyolchanyan  wrote:
> 
> Hi, Riley!
> 
> I think that's a great idea! We can merge the second part of my proposal (the 
> `indirect init`) into your one and refine and consolidate the prerequisite 
> proposal (about returning from `init` and possibly in-place member 
> initializers) and bunch them up into a proposal cluster (the way swift coders 
> did).
> Feel free to tear out any chunks from my proposal, while I think about a more 
> in-depth rationale about revamping initialization syntax. 
> 
>> On Jun 10, 2017, at 8:36 PM, Riley Testut > > wrote:
>> 
>> Hi Gor 
>> 
>> I’m very much in fan of a unified initialization syntax. I submitted my own 
>> proposal for factory initializers a while back, but since it wasn’t a focus 
>> of Swift 3 or 4 I haven’t followed up on it recently. In the time since last 
>> working on it, I came to my own conclusion that rather than focusing on 
>> factory initialization, the overall initialization process should be 
>> simplified, which I’m glad to see someone else has realized as well :-)
>> 
>> Here’s my proposal for reference: 
>> https://github.com/apple/swift-evolution/pull/247/commits/58b5a93b322aae998eb40574dee15fe54323de2e
>>  
>> 
>>  Originally I used the “factory” keyword, but I think your “indirect” 
>> keyword may be a better fit (since it has precedent in the language and is 
>> not limited to “just” being about factory initialization). To divide your 
>> proposal up into smaller pieces for review, maybe we could update my 
>> proposal to use your indirect keyword, and then start a separate 
>> topic/proposal for the remaining aspects of your proposal? I agree that 
>> splitting it into smaller chunks may be better for the process.
>> 
>> Let me know what you think!
>> 
>> Riley
>> 
>> 
>>> On Jun 10, 2017, at 3:33 AM, Gor Gyolchanyan via swift-evolution 
>>> > wrote:
>>> 
 
 This is a very interesting read.
 
>>> 
>>> Thanks you! I tried to make it as clear and detailed as possible.  
>>> 
 
 We did not discuss the 'indirect' idea at all on this list. Did you come 
 up with it just now? In any case, my suggestion as to moving forward would 
 be this:
 
>>> I was writing the proposal and was just about to write `factory init`, when 
>>> it occurred to me: enums already have a keyword that does something very 
>>> similar. It seemed to me that an initializer that doesn't initialize the 
>>> instance in-place, but returns a completely separate instance from 
>>> somewhere else, is kinda "indirectly" initializing the instance. Plus, the 
>>> already established keyword and its semantic would reduce the learning 
>>> curve for this new feature and separate it from a single specific use case 
>>> (the "factory method" pattern).
>>> 
 
 - Do you feel that both halves of your draft (expanding `return` in 
 initializers, and `indirect` initializers) should absolutely be one 
 proposal, or can they be separated?
 
>>> I think the `return` can be easily implemented first, while opening up an 
>>> opportunity to later implement `indirect init`. The reason why I unified 
>>> them was that the `return` idea on its own has very limited merit and could 
>>> the thought of as a low-priority cosmetic enhancement. I wouldn't want it 
>>> to be viewed that way because the primary purpose of that idea is to enable 
>>> `indirect init` (which Cocoa and Cocoa Touch developers would be very happy 
>>> about). 
>>> 
 
 a) If they can be separated because each half has individual merit, then 
 these ideas may be more likely to succeed as separate proposals, as each 
 can be critiqued fully and judged independently as digestible units.
 
>>> 
>>> Very good point. The challenge is to correctly separate them, without 
>>> losing context in their respective proposals and without bleeding the 
>>> proposals into each other.
>>> 
>>> 
 
>>> 
 b) If you intend to tackle all your ideas all at once, that's going to be 
 a much bigger change--in terms of review effort, likely bikeshedding, and 
 implementation effort. It'll probably be best to solicit initial feedback 
 on this list first about `indirect` initializers, even if just to 
 familiarize the community with the idea, before launching into a pitch of 
 the whole proposal.
 
>>> 
>>> I'd never send a pull request to swift-evolution without thoroughly 
>>> discussing it here. I 

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Paul Cantrell via swift-evolution
Being able to specify things about closure capturing at the API level could do 
wonders for Siesta — though its problems may be beyond the scope of what’s 
proposed here (or what’s workable at all).

Siesta exposes this API call:

someResource.addObserver(owner: self) {  // (1)
[weak self] resource, event in
…
self.bar()
…
}

…but it’s easy to forget that [weak self], and because of Siesta’s observer 
ownership rules:

http://bustoutsolutions.github.io/siesta/guide/memory/ 


…omitting it creates a retain cycle. This same problem also makes this 
otherwise lovely pattern untenable:

someResource.addObserver(owner: self, closure: self.fooUpdated) // (2)

To solve this problem, addObserver would need to be able to specify that the 
object passed as the owner should be weakly captured by the closure. It’s just 
that one specific •owner• object; everything else should be captured as usual. 
So it’s not a property of the closure itself, either in the type system or as 
an argument attribute; it’s a relationship between the closure and other args. 
Ouch!

At a glance, it looks like Matthew’s guarded closure proposal might solve this 
in practice for (2) but not for (1)?

In the absence of cycle detection, some way around this pitfall sure would be 
nice.

Cheers, P


> On Jun 10, 2017, at 12:49 PM, Gor Gyolchanyan via swift-evolution 
>  wrote:
> 
> The benefit that I can see here is the ability to guarantee memory safety on 
> API level, by way of specifying weak closure members. Previously, there way 
> no conceivable way of knowing that because a closure can essentially capture 
> whatever it wants (even the very object it's stored in), so this would be a 
> deterministic way of resolving *all* circular references caused by closures.
> 
> The downside is that it would require some heavy-duty closure capture 
> analysis on the compiler's part, so I'd expect it to be deferred to Swift 5 
> or something.
> However, this does play really nicely with the ownership concept that Swift 
> is going for.
> 
> I say, let's think this one through very thoroughly and write a very very 
> detailed proposal (including details on how would the core team get around 
> implementing this) and see what it looks like before submitting it.
> 
>> On Jun 10, 2017, at 8:29 PM, Adrian Zubarev via swift-evolution 
>> > wrote:
>> 
>> Hello Evolution,
>> 
>> I’d like to pitch a new idea and see where it would go. Recently I tapped 
>> into a small trap and just now realized that even that non-escaping should 
>> have been the default for closures (SE–0103) there is an exception for that. 
>> Apparently generics don’t follow that rule and a closure like 
>> 
>> Optional<() -> Void> or simply (() -> Void)?
>> 
>> is still escaping by default. But that was the half of the story yet. As we 
>> all know and “love” reference lists inside closures, methods don’t have any 
>> and we have to wrap method calls into a weak referenced closure 
>> 
>> { [weak self] in self.foo() }
>> 
>> to avoid strong reference cycles. Maybe you already guess it, I accidentally 
>> didn’t and tapped into the land of strong reference cycles yet again on my 
>> journey.
>> 
>> I’d like to pitch a new way, more like a new type behavior, for closures on 
>> how they could be used differently in order to avoid strong reference cycles 
>> but also providing the ability to use methods without any need to wrap them.
>> 
>> Here is a simple code snippet using RxSwift, which will recreate my issue:
>> 
>> import RxSwift
>> 
>> let test = PublishSubject()
>> 
>> class A {
>> 
>> let disposeBag = DisposeBag()
>> 
>> func foo() {
>> test.asObservable()
>> .subscribe(onNext: self.bar) // The issue is here
>> .disposed(by: self.disposeBag)
>> }
>> 
>> func bar() { print("works") }
>> }
>> 
>> let a = A()
>> a.foo()
>> 
>> test.onNext(()) // Testing if it works
>> test.onCompleted() // Some RxSwift stuff
>> In this case by passing directly the method self.bar we’re capturing self, 
>> which in this situation isn’t our intention at all. To avoid this issue we 
>> can simply wrap the method call into closure:
>> 
>> .subscribe(onNext: { [unowned self] in self.bar() })
>> 
>> (It’s safe to make it unowned because the dispose bag is a member of self.)
>> 
>> What if we had the ability for weak or unowned closures? By that I don’t 
>> mean weak/unowned references to the closures themselves, because they are 
>> also reference types, but an invalidation behavior for the whole closure 
>> based on the _captured_ references. For instance:
>> 
>> let closure1: weak (() -> Void)? = { self.doWhatever() }
>> 
>> let closure2: weak (() -> Void)? = self.doWhatever
>> 
>> If one would now try to call the closure, first it will check if all the 
>> captured 

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
If weak closures ever become a thing, I do think that the implicit strong 
promotion of the closure's captures should never happen and instead, the 
closure should be manually optional-unwrapped before it's called, so that the 
existing safety guarantees of weak object references would persist.

> On Jun 10, 2017, at 11:04 PM, Adrian Zubarev 
>  wrote:
> 
> Just a few more replies from John McCall:
> 
> You want to invalidate the closure value based on whether any of its captures 
> have been invalidated.
> 
> It’s an interesting idea, but it’s quite complex because an invalidatable 
> closure is definitely a different sort of thing from a normal one.
> 
> So like you say, it would need to be tracked in the type, which is not the 
> language model we otherwise use for closures. Er, for weak/unowned, I mean.
> 
> The behavior for unowned is not too different from the current behavior, so 
> it’s really mostly about weak.
> 
> I guess the captured reference becomes strong immediately, protecting against 
> it going away during the closure.
> 
> But unowned is conventionally used in cases where that isn’t going to happen 
> anyway.
> 
> The semantics of testing a “weak closure” are not obvious. Always must be 
> wrapped in optional, unwrapping it gives a value of non-weak type?
> 
> Totally different from normal optional behavior on values, but I guess it 
> works.
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 10. Juni 2017 um 21:58:21, Adrian Zubarev (adrian.zuba...@devandartist.com 
> ) schrieb:
> 
>> Well I simply reused the existing keywords as part of the closure type to 
>> demonstrate the idea here as easy as possible.
>> 
>> About the _true_ weak/unowned closures. First I asked John McCall on twitter 
>> about this whole idea. Here is his reply about the _true_ weak closures:
>> 
>> You mean a weak reference to a closure? No, I don’t think we’d ever want to 
>> assign closure values enough identity to give that meaning.
>> I get it, that it might be not quite obvious or even confusing why 
>> weak/unowned can be applied on a type and on a variable. However weak is 
>> always an Optional or an IUO where unowned is non-optional.
>> 
>> Just my personal thoughts: Could we potentially align weak/unowned with 
>> inout and make it type decoration? (This would be a breaking change.)
>> 
>> 
>> 
>> -- 
>> Adrian Zubarev
>> Sent with Airmail
>> 
>> Am 10. Juni 2017 um 21:44:41, Gor Gyolchanyan (g...@gyolchanyan.com 
>> ) schrieb:
>> 
>>> I don't think it's a good idea to make the `weak`-ness of the closure part 
>>> of the type system.
>>> The current approach to `weak/unowned` is that it's a storage class that 
>>> applies to the variable, not the value.
>>> This makes sense because you don't *use* a weak reference, you only *store* 
>>> it weakly.
>>> I think this behavior has to stay the same with the addition of closures 
>>> (being the other reference type along classes) would be eligible for 
>>> storing by `weak/unowned` reference.
>>> 
 On Jun 10, 2017, at 10:39 PM, Adrian Zubarev via swift-evolution 
 > wrote:
 
 Hi Matthew,
 
 Thank you for the hint. Indeed, at first glance your proposal is very 
 similar to my thinking. I’ll try to dive deeper into your proposal and 
 find out more about the discussion behind it when I get some more time for 
 that.
 
 We could collaborate on a revision for Swift 5 if you would like to, but 
 we wouldn’t need to rush now, because there is plenty of time for that. 
 
 Personally I would love to avoid some kind of a prefix like ? if possible.
 
 Brainstorming:
 
 let c1 = weak someObject.method convert it to a weak closure.
 
 let c2: weak (CLOSURETYPE)? = someObject.method Let the compiler do the 
 job for us.
 
 The latter would be great for APIs to avoid the prefix.
 
 .subscribe(onNext: self.bar) weak is inferred and can be omitted 
 
 
 
 
 -- 
 Adrian Zubarev
 Sent with Airmail
 
 Am 10. Juni 2017 um 21:09:28, Matthew Johnson (matt...@anandabits.com 
 ) schrieb:
 
> Hi Adrian, this is pretty similar to the Guarded Closures proposal I 
> drafted in February.  This proposal needs a revision incorporating 
> discussion feedback and some new ideas.  If you’re interested, here’s a 
> link to the original discussion thread: 
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032478.html
>  
> .
> 
>> On Jun 10, 2017, at 12:29 PM, Adrian Zubarev via swift-evolution 
>> > wrote:
>> 
>> Hello Evolution,
>> 

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Adrian Zubarev via swift-evolution
Just a few more replies from John McCall:

You want to invalidate the closure value based on whether any of its captures 
have been invalidated.

It’s an interesting idea, but it’s quite complex because an invalidatable 
closure is definitely a different sort of thing from a normal one.

So like you say, it would need to be tracked in the type, which is not the 
language model we otherwise use for closures. Er, for weak/unowned, I mean.

The behavior for unowned is not too different from the current behavior, so 
it’s really mostly about weak.

I guess the captured reference becomes strong immediately, protecting against 
it going away during the closure.

But unowned is conventionally used in cases where that isn’t going to happen 
anyway.

The semantics of testing a “weak closure” are not obvious. Always must be 
wrapped in optional, unwrapping it gives a value of non-weak type?

Totally different from normal optional behavior on values, but I guess it works.


-- 
Adrian Zubarev
Sent with Airmail

Am 10. Juni 2017 um 21:58:21, Adrian Zubarev (adrian.zuba...@devandartist.com) 
schrieb:

Well I simply reused the existing keywords as part of the closure type to 
demonstrate the idea here as easy as possible.

About the _true_ weak/unowned closures. First I asked John McCall on twitter 
about this whole idea. Here is his reply about the _true_ weak closures:

You mean a weak reference to a closure? No, I don’t think we’d ever want to 
assign closure values enough identity to give that meaning.
I get it, that it might be not quite obvious or even confusing why weak/unowned 
can be applied on a type and on a variable. However weak is always an Optional 
or an IUO where unowned is non-optional.

Just my personal thoughts: Could we potentially align weak/unowned with inout 
and make it type decoration? (This would be a breaking change.)



-- 
Adrian Zubarev
Sent with Airmail

Am 10. Juni 2017 um 21:44:41, Gor Gyolchanyan (g...@gyolchanyan.com) schrieb:

I don't think it's a good idea to make the `weak`-ness of the closure part of 
the type system.
The current approach to `weak/unowned` is that it's a storage class that 
applies to the variable, not the value.
This makes sense because you don't *use* a weak reference, you only *store* it 
weakly.
I think this behavior has to stay the same with the addition of closures (being 
the other reference type along classes) would be eligible for storing by 
`weak/unowned` reference.

On Jun 10, 2017, at 10:39 PM, Adrian Zubarev via swift-evolution 
 wrote:

Hi Matthew,

Thank you for the hint. Indeed, at first glance your proposal is very similar 
to my thinking. I’ll try to dive deeper into your proposal and find out more 
about the discussion behind it when I get some more time for that.

We could collaborate on a revision for Swift 5 if you would like to, but we 
wouldn’t need to rush now, because there is plenty of time for that. 

Personally I would love to avoid some kind of a prefix like ? if possible.

Brainstorming:

let c1 = weak someObject.method convert it to a weak closure.

let c2: weak (CLOSURETYPE)? = someObject.method Let the compiler do the job for 
us.

The latter would be great for APIs to avoid the prefix.

.subscribe(onNext: self.bar) weak is inferred and can be omitted 




-- 
Adrian Zubarev
Sent with Airmail

Am 10. Juni 2017 um 21:09:28, Matthew Johnson (matt...@anandabits.com) schrieb:

Hi Adrian, this is pretty similar to the Guarded Closures proposal I drafted in 
February.  This proposal needs a revision incorporating discussion feedback and 
some new ideas.  If you’re interested, here’s a link to the original discussion 
thread: 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032478.html.

On Jun 10, 2017, at 12:29 PM, Adrian Zubarev via swift-evolution 
 wrote:

Hello Evolution,

I’d like to pitch a new idea and see where it would go. Recently I tapped into 
a small trap and just now realized that even that non-escaping should have been 
the default for closures (SE–0103) there is an exception for that. Apparently 
generics don’t follow that rule and a closure like 

Optional<() -> Void> or simply (() -> Void)?

is still escaping by default. But that was the half of the story yet. As we all 
know and “love” reference lists inside closures, methods don’t have any and we 
have to wrap method calls into a weak referenced closure 

{ [weak self] in self.foo() }

to avoid strong reference cycles. Maybe you already guess it, I accidentally 
didn’t and tapped into the land of strong reference cycles yet again on my 
journey.

I’d like to pitch a new way, more like a new type behavior, for closures on how 
they could be used differently in order to avoid strong reference cycles but 
also providing the ability to use methods without any need to wrap them.

Here is a simple code snippet using RxSwift, which will recreate my issue:

import RxSwift

let test = 

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Adrian Zubarev via swift-evolution
Well I simply reused the existing keywords as part of the closure type to 
demonstrate the idea here as easy as possible.

About the _true_ weak/unowned closures. First I asked John McCall on twitter 
about this whole idea. Here is his reply about the _true_ weak closures:

You mean a weak reference to a closure? No, I don’t think we’d ever want to 
assign closure values enough identity to give that meaning.
I get it, that it might be not quite obvious or even confusing why weak/unowned 
can be applied on a type and on a variable. However weak is always an Optional 
or an IUO where unowned is non-optional.

Just my personal thoughts: Could we potentially align weak/unowned with inout 
and make it type decoration? (This would be a breaking change.)



-- 
Adrian Zubarev
Sent with Airmail

Am 10. Juni 2017 um 21:44:41, Gor Gyolchanyan (g...@gyolchanyan.com) schrieb:

I don't think it's a good idea to make the `weak`-ness of the closure part of 
the type system.
The current approach to `weak/unowned` is that it's a storage class that 
applies to the variable, not the value.
This makes sense because you don't *use* a weak reference, you only *store* it 
weakly.
I think this behavior has to stay the same with the addition of closures (being 
the other reference type along classes) would be eligible for storing by 
`weak/unowned` reference.

On Jun 10, 2017, at 10:39 PM, Adrian Zubarev via swift-evolution 
 wrote:

Hi Matthew,

Thank you for the hint. Indeed, at first glance your proposal is very similar 
to my thinking. I’ll try to dive deeper into your proposal and find out more 
about the discussion behind it when I get some more time for that.

We could collaborate on a revision for Swift 5 if you would like to, but we 
wouldn’t need to rush now, because there is plenty of time for that. 

Personally I would love to avoid some kind of a prefix like ? if possible.

Brainstorming:

let c1 = weak someObject.method convert it to a weak closure.

let c2: weak (CLOSURETYPE)? = someObject.method Let the compiler do the job for 
us.

The latter would be great for APIs to avoid the prefix.

.subscribe(onNext: self.bar) weak is inferred and can be omitted 




-- 
Adrian Zubarev
Sent with Airmail

Am 10. Juni 2017 um 21:09:28, Matthew Johnson (matt...@anandabits.com) schrieb:

Hi Adrian, this is pretty similar to the Guarded Closures proposal I drafted in 
February.  This proposal needs a revision incorporating discussion feedback and 
some new ideas.  If you’re interested, here’s a link to the original discussion 
thread: 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032478.html.

On Jun 10, 2017, at 12:29 PM, Adrian Zubarev via swift-evolution 
 wrote:

Hello Evolution,

I’d like to pitch a new idea and see where it would go. Recently I tapped into 
a small trap and just now realized that even that non-escaping should have been 
the default for closures (SE–0103) there is an exception for that. Apparently 
generics don’t follow that rule and a closure like 

Optional<() -> Void> or simply (() -> Void)?

is still escaping by default. But that was the half of the story yet. As we all 
know and “love” reference lists inside closures, methods don’t have any and we 
have to wrap method calls into a weak referenced closure 

{ [weak self] in self.foo() }

to avoid strong reference cycles. Maybe you already guess it, I accidentally 
didn’t and tapped into the land of strong reference cycles yet again on my 
journey.

I’d like to pitch a new way, more like a new type behavior, for closures on how 
they could be used differently in order to avoid strong reference cycles but 
also providing the ability to use methods without any need to wrap them.

Here is a simple code snippet using RxSwift, which will recreate my issue:

import RxSwift

let test = PublishSubject()

class A {

let disposeBag = DisposeBag()

func foo() {
test.asObservable()
.subscribe(onNext: self.bar) // The issue is here
.disposed(by: self.disposeBag)
}

func bar() { print("works") }
}

let a = A()
a.foo()

test.onNext(()) // Testing if it works
test.onCompleted() // Some RxSwift stuff
In this case by passing directly the method self.bar we’re capturing self, 
which in this situation isn’t our intention at all. To avoid this issue we can 
simply wrap the method call into closure:

.subscribe(onNext: { [unowned self] in self.bar() })

(It’s safe to make it unowned because the dispose bag is a member of self.)

What if we had the ability for weak or unowned closures? By that I don’t mean 
weak/unowned references to the closures themselves, because they are also 
reference types, but an invalidation behavior for the whole closure based on 
the _captured_ references. For instance:

let closure1: weak (() -> Void)? = { self.doWhatever() }

let closure2: weak (() -> Void)? = self.doWhatever

If one would now try to call the closure, 

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
I don't think it's a good idea to make the `weak`-ness of the closure part of 
the type system.
The current approach to `weak/unowned` is that it's a storage class that 
applies to the variable, not the value.
This makes sense because you don't *use* a weak reference, you only *store* it 
weakly.
I think this behavior has to stay the same with the addition of closures (being 
the other reference type along classes) would be eligible for storing by 
`weak/unowned` reference.

> On Jun 10, 2017, at 10:39 PM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> Hi Matthew,
> 
> Thank you for the hint. Indeed, at first glance your proposal is very similar 
> to my thinking. I’ll try to dive deeper into your proposal and find out more 
> about the discussion behind it when I get some more time for that.
> 
> We could collaborate on a revision for Swift 5 if you would like to, but we 
> wouldn’t need to rush now, because there is plenty of time for that. 
> 
> Personally I would love to avoid some kind of a prefix like ? if possible.
> 
> Brainstorming:
> 
> let c1 = weak someObject.method convert it to a weak closure.
> 
> let c2: weak (CLOSURETYPE)? = someObject.method Let the compiler do the job 
> for us.
> 
> The latter would be great for APIs to avoid the prefix.
> 
> .subscribe(onNext: self.bar) weak is inferred and can be omitted 
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> Am 10. Juni 2017 um 21:09:28, Matthew Johnson (matt...@anandabits.com 
> ) schrieb:
> 
>> Hi Adrian, this is pretty similar to the Guarded Closures proposal I drafted 
>> in February.  This proposal needs a revision incorporating discussion 
>> feedback and some new ideas.  If you’re interested, here’s a link to the 
>> original discussion thread: 
>> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032478.html
>>  
>> .
>> 
>>> On Jun 10, 2017, at 12:29 PM, Adrian Zubarev via swift-evolution 
>>> > wrote:
>>> 
>>> Hello Evolution,
>>> 
>>> I’d like to pitch a new idea and see where it would go. Recently I tapped 
>>> into a small trap and just now realized that even that non-escaping should 
>>> have been the default for closures (SE–0103) there is an exception for 
>>> that. Apparently generics don’t follow that rule and a closure like 
>>> 
>>> Optional<() -> Void> or simply (() -> Void)?
>>> 
>>> is still escaping by default. But that was the half of the story yet. As we 
>>> all know and “love” reference lists inside closures, methods don’t have any 
>>> and we have to wrap method calls into a weak referenced closure 
>>> 
>>> { [weak self] in self.foo() }
>>> 
>>> to avoid strong reference cycles. Maybe you already guess it, I 
>>> accidentally didn’t and tapped into the land of strong reference cycles yet 
>>> again on my journey.
>>> 
>>> I’d like to pitch a new way, more like a new type behavior, for closures on 
>>> how they could be used differently in order to avoid strong reference 
>>> cycles but also providing the ability to use methods without any need to 
>>> wrap them.
>>> 
>>> Here is a simple code snippet using RxSwift, which will recreate my issue:
>>> 
>>> import RxSwift
>>> 
>>> let test = PublishSubject()
>>> 
>>> class A {
>>> 
>>> let disposeBag = DisposeBag()
>>> 
>>> func foo() {
>>> test.asObservable()
>>> .subscribe(onNext: self.bar) // The issue is here
>>> .disposed(by: self.disposeBag)
>>> }
>>> 
>>> func bar() { print("works") }
>>> }
>>> 
>>> let a = A()
>>> a.foo()
>>> 
>>> test.onNext(()) // Testing if it works
>>> test.onCompleted() // Some RxSwift stuff
>>> In this case by passing directly the method self.bar we’re capturing self, 
>>> which in this situation isn’t our intention at all. To avoid this issue we 
>>> can simply wrap the method call into closure:
>>> 
>>> .subscribe(onNext: { [unowned self] in self.bar() })
>>> 
>>> (It’s safe to make it unowned because the dispose bag is a member of self.)
>>> 
>>> What if we had the ability for weak or unowned closures? By that I don’t 
>>> mean weak/unowned references to the closures themselves, because they are 
>>> also reference types, but an invalidation behavior for the whole closure 
>>> based on the _captured_ references. For instance:
>>> 
>>> let closure1: weak (() -> Void)? = { self.doWhatever() }
>>> 
>>> let closure2: weak (() -> Void)? = self.doWhatever
>>> 
>>> If one would now try to call the closure, first it will check if all the 
>>> captured objects are still available or not, if not the whole closure in 
>>> this case will simply become nil and won’t execute. In case of unowned 
>>> closures it will trap. Furthermore it will support the general meaning of 
>>> weak/unowned and will not increase the reference counter for *captured 
>>> objects*.

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Adrian Zubarev via swift-evolution
Hi Matthew,

Thank you for the hint. Indeed, at first glance your proposal is very similar 
to my thinking. I’ll try to dive deeper into your proposal and find out more 
about the discussion behind it when I get some more time for that.

We could collaborate on a revision for Swift 5 if you would like to, but we 
wouldn’t need to rush now, because there is plenty of time for that.

Personally I would love to avoid some kind of a prefix like ? if possible.

Brainstorming:

let c1 = weak someObject.method convert it to a weak closure.

let c2: weak (CLOSURETYPE)? = someObject.method Let the compiler do the job for 
us.

The latter would be great for APIs to avoid the prefix.

.subscribe(onNext: self.bar) weak is inferred and can be omitted



-- 
Adrian Zubarev
Sent with Airmail

Am 10. Juni 2017 um 21:09:28, Matthew Johnson (matt...@anandabits.com) schrieb:

Hi Adrian, this is pretty similar to the Guarded Closures proposal I drafted in 
February.  This proposal needs a revision incorporating discussion feedback and 
some new ideas.  If you’re interested, here’s a link to the original discussion 
thread: 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032478.html.

On Jun 10, 2017, at 12:29 PM, Adrian Zubarev via swift-evolution 
 wrote:

Hello Evolution,

I’d like to pitch a new idea and see where it would go. Recently I tapped into 
a small trap and just now realized that even that non-escaping should have been 
the default for closures (SE–0103) there is an exception for that. Apparently 
generics don’t follow that rule and a closure like 

Optional<() -> Void> or simply (() -> Void)?

is still escaping by default. But that was the half of the story yet. As we all 
know and “love” reference lists inside closures, methods don’t have any and we 
have to wrap method calls into a weak referenced closure 

{ [weak self] in self.foo() }

to avoid strong reference cycles. Maybe you already guess it, I accidentally 
didn’t and tapped into the land of strong reference cycles yet again on my 
journey.

I’d like to pitch a new way, more like a new type behavior, for closures on how 
they could be used differently in order to avoid strong reference cycles but 
also providing the ability to use methods without any need to wrap them.

Here is a simple code snippet using RxSwift, which will recreate my issue:

import RxSwift

let test = PublishSubject()

class A {

let disposeBag = DisposeBag()

func foo() {
test.asObservable()
.subscribe(onNext: self.bar) // The issue is here
.disposed(by: self.disposeBag)
}

func bar() { print("works") }
}

let a = A()
a.foo()

test.onNext(()) // Testing if it works
test.onCompleted() // Some RxSwift stuff
In this case by passing directly the method self.bar we’re capturing self, 
which in this situation isn’t our intention at all. To avoid this issue we can 
simply wrap the method call into closure:

.subscribe(onNext: { [unowned self] in self.bar() })

(It’s safe to make it unowned because the dispose bag is a member of self.)

What if we had the ability for weak or unowned closures? By that I don’t mean 
weak/unowned references to the closures themselves, because they are also 
reference types, but an invalidation behavior for the whole closure based on 
the _captured_ references. For instance:

let closure1: weak (() -> Void)? = { self.doWhatever() }

let closure2: weak (() -> Void)? = self.doWhatever

If one would now try to call the closure, first it will check if all the 
captured objects are still available or not, if not the whole closure in this 
case will simply become nil and won’t execute. In case of unowned closures it 
will trap. Furthermore it will support the general meaning of weak/unowned and 
will not increase the reference counter for *captured objects*.

As you have already noticed, in this case the convention is slightly different 
because we must carry the behavior directly with the type.

func subscribe(onNext: weak ((Swift.E) -> Void)?)

If the way of my thinking is correct this idea _could maybe_ fade out the very 
common [weak self] in guard let strongSelf = self … pattern. 

I personally cannot tell all the technical difficulties this idea might have, 
but that’s what the evolution list is for, to collaboratively flesh out the 
ideas if they are worth it.

If something like this could be possible it’s probably worth noting that we 
might also be able to introduce something like @autoclosure(weak/unowned) to 
Swift for consistency.




-- 
Adrian Zubarev
Sent with Airmail

___
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 map and flatMap with smart key paths

2017-06-10 Thread David Hart via swift-evolution


> On 9 Jun 2017, at 19:06, Max Moiseev via swift-evolution 
>  wrote:
> 
> Sorry. I might be missing something. Why is this better than:
> 
> let allEmployees = Set(managers.flatMap { $0.directReports }
> 
> ?

For the same reasons

managers.flatMap(calculateReports(_:))

Is better than:

managers.flatMap { calculateReports($0) }

Quite a few people enjoy this tearse, functional style.

>> On Jun 7, 2017, at 10:35 AM, Adam Sharp via swift-evolution 
>>  wrote:
>> 
>> The new smart key path feature is really lovely, and feels like a great 
>> addition to Swift.
>> 
>> It seems like it might be straightforward to add overloads of `map` and 
>> `flatMap` to the standard library to make use of the new functionality:
>> 
>>let managers = flatOrganisation.managers
>>let allEmployees = Set(managers.flatMap(\.directReports))
>>let employeeNames = Set(allEmployees.map(\.name))
>> 
>> This feels like a really natural way of working with key paths in a 
>> functional style. It makes a lot of sense for collections, and possibly for 
>> Optional too (although as far as I can see optional chaining is more or less 
>> equivalent, and with more compact syntax).
>> 
>> I’m hoping that this might be low-hanging fruit that could be considered for 
>> the Swift 4 release. I’d be happy to have a go at writing a proposal if 
>> there’s interest!
>> 
>> –Adam
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Matthew Johnson via swift-evolution
Hi Adrian, this is pretty similar to the Guarded Closures proposal I drafted in 
February.  This proposal needs a revision incorporating discussion feedback and 
some new ideas.  If you’re interested, here’s a link to the original discussion 
thread: 
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032478.html
 
.

> On Jun 10, 2017, at 12:29 PM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> Hello Evolution,
> 
> I’d like to pitch a new idea and see where it would go. Recently I tapped 
> into a small trap and just now realized that even that non-escaping should 
> have been the default for closures (SE–0103) there is an exception for that. 
> Apparently generics don’t follow that rule and a closure like 
> 
> Optional<() -> Void> or simply (() -> Void)?
> 
> is still escaping by default. But that was the half of the story yet. As we 
> all know and “love” reference lists inside closures, methods don’t have any 
> and we have to wrap method calls into a weak referenced closure 
> 
> { [weak self] in self.foo() }
> 
> to avoid strong reference cycles. Maybe you already guess it, I accidentally 
> didn’t and tapped into the land of strong reference cycles yet again on my 
> journey.
> 
> I’d like to pitch a new way, more like a new type behavior, for closures on 
> how they could be used differently in order to avoid strong reference cycles 
> but also providing the ability to use methods without any need to wrap them.
> 
> Here is a simple code snippet using RxSwift, which will recreate my issue:
> 
> import RxSwift
> 
> let test = PublishSubject()
> 
> class A {
> 
> let disposeBag = DisposeBag()
> 
> func foo() {
> test.asObservable()
> .subscribe(onNext: self.bar) // The issue is here
> .disposed(by: self.disposeBag)
> }
> 
> func bar() { print("works") }
> }
> 
> let a = A()
> a.foo()
> 
> test.onNext(()) // Testing if it works
> test.onCompleted() // Some RxSwift stuff
> In this case by passing directly the method self.bar we’re capturing self, 
> which in this situation isn’t our intention at all. To avoid this issue we 
> can simply wrap the method call into closure:
> 
> .subscribe(onNext: { [unowned self] in self.bar() })
> 
> (It’s safe to make it unowned because the dispose bag is a member of self.)
> 
> What if we had the ability for weak or unowned closures? By that I don’t mean 
> weak/unowned references to the closures themselves, because they are also 
> reference types, but an invalidation behavior for the whole closure based on 
> the _captured_ references. For instance:
> 
> let closure1: weak (() -> Void)? = { self.doWhatever() }
> 
> let closure2: weak (() -> Void)? = self.doWhatever
> 
> If one would now try to call the closure, first it will check if all the 
> captured objects are still available or not, if not the whole closure in this 
> case will simply become nil and won’t execute. In case of unowned closures it 
> will trap. Furthermore it will support the general meaning of weak/unowned 
> and will not increase the reference counter for *captured objects*.
> 
> As you have already noticed, in this case the convention is slightly 
> different because we must carry the behavior directly with the type.
> 
> func subscribe(onNext: weak ((Swift.E) -> Void)?)
> 
> If the way of my thinking is correct this idea _could maybe_ fade out the 
> very common [weak self] in guard let strongSelf = self … pattern. 
> 
> I personally cannot tell all the technical difficulties this idea might have, 
> but that’s what the evolution list is for, to collaboratively flesh out the 
> ideas if they are worth it.
> 
> If something like this could be possible it’s probably worth noting that we 
> might also be able to introduce something like @autoclosure(weak/unowned) to 
> Swift for consistency.
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> ___
> 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] Introduction of `weak/unowned` closures

2017-06-10 Thread old donkey via swift-evolution
Agree with Gor, this can work nicely with ownership concept.Though it will 
require a lot of compiler analysis, I think as Swift’s goal is to be a safer 
language, still worth it.

I like this idea. But yes, we need a more detail proposal, this need a lot of 
work.

On 2017年6月10日 -0700 AM10:49, Gor Gyolchanyan via swift-evolution 
, wrote:
> The benefit that I can see here is the ability to guarantee memory safety on 
> API level, by way of specifying weak closure members. Previously, there way 
> no conceivable way of knowing that because a closure can essentially capture 
> whatever it wants (even the very object it's stored in), so this would be a 
> deterministic way of resolving *all* circular references caused by closures.
>
> The downside is that it would require some heavy-duty closure capture 
> analysis on the compiler's part, so I'd expect it to be deferred to Swift 5 
> or something.
> However, this does play really nicely with the ownership concept that Swift 
> is going for.
>
> I say, let's think this one through very thoroughly and write a very very 
> detailed proposal (including details on how would the core team get around 
> implementing this) and see what it looks like before submitting it.
>
> > On Jun 10, 2017, at 8:29 PM, Adrian Zubarev via swift-evolution 
> >  wrote:
> >
> > Hello Evolution,
> > I’d like to pitch a new idea and see where it would go. Recently I tapped 
> > into a small trap and just now realized that even that non-escaping should 
> > have been the default for closures (SE–0103) there is an exception for 
> > that. Apparently generics don’t follow that rule and a closure like
> > Optional<() -> Void> or simply (() -> Void)?
> > is still escaping by default. But that was the half of the story yet. As we 
> > all know and “love” reference lists inside closures, methods don’t have any 
> > and we have to wrap method calls into a weak referenced closure
> > { [weak self] in self.foo() }
> > to avoid strong reference cycles. Maybe you already guess it, I 
> > accidentally didn’t and tapped into the land of strong reference cycles yet 
> > again on my journey.
> > I’d like to pitch a new way, more like a new type behavior, for closures on 
> > how they could be used differently in order to avoid strong reference 
> > cycles but also providing the ability to use methods without any need to 
> > wrap them.
> > Here is a simple code snippet using RxSwift, which will recreate my issue:
> >
> > import RxSwift
> >
> > let test = PublishSubject()
> >
> > class A {
> >
> >let disposeBag = DisposeBag()
> >
> >func foo() {
> >test.asObservable()
> >.subscribe(onNext: self.bar) // The issue is here
> >.disposed(by: self.disposeBag)
> >}
> >
> >func bar() { print("works") }
> > }
> >
> > let a = A()
> > a.foo()
> >
> > test.onNext(()) // Testing if it works
> > test.onCompleted() // Some RxSwift stuff
> >
> > In this case by passing directly the method self.bar we’re capturing self, 
> > which in this situation isn’t our intention at all. To avoid this issue we 
> > can simply wrap the method call into closure:
> > .subscribe(onNext: { [unowned self] in self.bar() })
> > (It’s safe to make it unowned because the dispose bag is a member of self.)
> > What if we had the ability for weak or unowned closures? By that I don’t 
> > mean weak/unowned references to the closures themselves, because they are 
> > also reference types, but an invalidation behavior for the whole closure 
> > based on the _captured_ references. For instance:
> > let closure1: weak (() -> Void)? = { self.doWhatever() }
> > let closure2: weak (() -> Void)? = self.doWhatever
> > If one would now try to call the closure, first it will check if all the 
> > captured objects are still available or not, if not the whole closure in 
> > this case will simply become nil and won’t execute. In case of unowned 
> > closures it will trap. Furthermore it will support the general meaning of 
> > weak/unowned and will not increase the reference counter for *captured 
> > objects*.
> > As you have already noticed, in this case the convention is slightly 
> > different because we must carry the behavior directly with the type.
> > func subscribe(onNext: weak ((Swift.E) -> Void)?)
> > If the way of my thinking is correct this idea _could maybe_ fade out the 
> > very common [weak self] in guard let strongSelf = self … pattern.
> > I personally cannot tell all the technical difficulties this idea might 
> > have, but that’s what the evolution list is for, to collaboratively flesh 
> > out the ideas if they are worth it.
> > If something like this could be possible it’s probably worth noting that we 
> > might also be able to introduce something like @autoclosure(weak/unowned) 
> > to Swift for consistency.
> >
> >
> >
> > --
> > Adrian Zubarev
> > Sent with Airmail
> >
> > ___
> > 

Re: [swift-evolution] [Pitch] #error

2017-06-10 Thread Xiaodi Wu via swift-evolution
Daryle, there have been several pitches in the past with respect to #error,
and very enlightening arguments both for and against the idea have been
eloquently written.

Since you’re resurrecting this idea, could I suggest going back through the
archives and linking to and summarizing these arguments, so that we’re not
restarting the discussion from scratch? :)


On Sat, Jun 10, 2017 at 13:26 Gor Gyolchanyan via swift-evolution <
swift-evolution@swift.org> wrote:

> Love it! Except I'd add `warning` as well.
>
>
> On Jun 10, 2017, at 8:15 PM, Daryle Walker via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Unconditional Error Messages
>
>- Proposal: SE-
>- Authors: Daryle Walker , Author 2
>
>- Review Manager: TBD
>- Status: *Awaiting review*
>
> *During the review process, add the following fields as needed:*
>
>- Decision Notes: Rationale
>, Additional
>Commentary 
>- Bugs: SR- , SR-
>
>- Previous Revision: 1
>
> 
>- Previous Proposal: SE-
>
> Introduction
>
> This proposal adds the #error directive, which unconditionally posts a
> compile-time error.
>
> Swift-evolution thread: Discussion thread topic for that proposal
> 
> Motivation
>
> A conditional compilation block permits branches of code based on the
> compilation conditions.
>
> #if compilation condition 1
> // statements to compile if compilation condition 1 is true
> #elseif compilation condition 2
> // statements to compile if compilation condition 2 is true
> #else
> // statements to compile if both compilation conditions are false
> #endif
>
> A block lets at most one of its branches to be incorporated into the
> compiled module. But compilation always occurs; there is no scenario to
> flag conditions that should never allow compiling.
>
> When suspending work on a source file for a while, marking where you ended
> work with an unconditional error message would let the compiler remind you
> where you left off.
> Proposed solution
>
> The solution is to add a new compiler control statement, one that posts a
> fatal diagnostic during compilation. It can include a message to aid the
> user on how to change their code.
>
> It's called #error, after the C preprocessor directive that has the same
> effects.
>
> For example, instead of checking API compatibility at run-time:
>
> guard #available(tvOS 1.0, *) else {
> fatalError("We need a TV.")
> }
>
> // Do what we're supposed to do
>
> We can move the check to compile-time:
>
> #if os(tvOS)
> // Do what we're supposed to do
> #else
> #error("We need a TV.")
> #endif
>
> Detailed design
>
> Add to the "Grammar of a Compiler Control Statement":
>
> *compiler-control-statement* → *error-directive-statement­*
>
> Add a new section "Grammar of a Error Directive Statement":
>
> *error-directive-statement* → *#error* *(* *static-string-literal* *)*
>
> The semantics of an error directive statement are: when such a statement
> is encountered during translation, and it is not in an inactive compilation
> block branch, compilation is aborted and the directive's string is included
> in the diagnostic of the directive's source line.
> Source compatibility
>
> This proposal should cause no problems with source compatibility. Relative
> to the current grammar, there is an addition of one token: #error. Since
> #-leading tokens are illegal except for the explicitly defined ones, there
> is no possibly of token overlap in legacy code.
> Effect on ABI stability
>
> Since the domain of this proposal is all in the compilation phase of
> creating object code, there is no effect on ABI stability.
> Effect on API resilience
>
> The domain of this proposal, controlling whether translation completes,
> does not affect any API.
> Alternatives considered
>
> The alternative is to do nothing. This would mean any checks would stay
> being delayed into run-time, and calling fatalError or similar functions
> to avoid implementing uncovered compilation cases.
>
> The original C syntax left open tokens as the message after the #error token.
> I decided to enclose the message as a string to ease parsing.
> Future directions
>
> The original idea for this proposal was a distraction while bringing an
> adaptation of C++'s static_assert, as defined in its proposal
> . The
> static_assert is a condition-checking mechanic between assert and #error;
> Swift already has the former and this proposal would bring the latter.
> There'd still be no equivalent for static_assert. Another proposal for
> 

Re: [swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
The benefit that I can see here is the ability to guarantee memory safety on 
API level, by way of specifying weak closure members. Previously, there way no 
conceivable way of knowing that because a closure can essentially capture 
whatever it wants (even the very object it's stored in), so this would be a 
deterministic way of resolving *all* circular references caused by closures.

The downside is that it would require some heavy-duty closure capture analysis 
on the compiler's part, so I'd expect it to be deferred to Swift 5 or something.
However, this does play really nicely with the ownership concept that Swift is 
going for.

I say, let's think this one through very thoroughly and write a very very 
detailed proposal (including details on how would the core team get around 
implementing this) and see what it looks like before submitting it.

> On Jun 10, 2017, at 8:29 PM, Adrian Zubarev via swift-evolution 
>  wrote:
> 
> Hello Evolution,
> 
> I’d like to pitch a new idea and see where it would go. Recently I tapped 
> into a small trap and just now realized that even that non-escaping should 
> have been the default for closures (SE–0103) there is an exception for that. 
> Apparently generics don’t follow that rule and a closure like 
> 
> Optional<() -> Void> or simply (() -> Void)?
> 
> is still escaping by default. But that was the half of the story yet. As we 
> all know and “love” reference lists inside closures, methods don’t have any 
> and we have to wrap method calls into a weak referenced closure 
> 
> { [weak self] in self.foo() }
> 
> to avoid strong reference cycles. Maybe you already guess it, I accidentally 
> didn’t and tapped into the land of strong reference cycles yet again on my 
> journey.
> 
> I’d like to pitch a new way, more like a new type behavior, for closures on 
> how they could be used differently in order to avoid strong reference cycles 
> but also providing the ability to use methods without any need to wrap them.
> 
> Here is a simple code snippet using RxSwift, which will recreate my issue:
> 
> import RxSwift
> 
> let test = PublishSubject()
> 
> class A {
> 
> let disposeBag = DisposeBag()
> 
> func foo() {
> test.asObservable()
> .subscribe(onNext: self.bar) // The issue is here
> .disposed(by: self.disposeBag)
> }
> 
> func bar() { print("works") }
> }
> 
> let a = A()
> a.foo()
> 
> test.onNext(()) // Testing if it works
> test.onCompleted() // Some RxSwift stuff
> In this case by passing directly the method self.bar we’re capturing self, 
> which in this situation isn’t our intention at all. To avoid this issue we 
> can simply wrap the method call into closure:
> 
> .subscribe(onNext: { [unowned self] in self.bar() })
> 
> (It’s safe to make it unowned because the dispose bag is a member of self.)
> 
> What if we had the ability for weak or unowned closures? By that I don’t mean 
> weak/unowned references to the closures themselves, because they are also 
> reference types, but an invalidation behavior for the whole closure based on 
> the _captured_ references. For instance:
> 
> let closure1: weak (() -> Void)? = { self.doWhatever() }
> 
> let closure2: weak (() -> Void)? = self.doWhatever
> 
> If one would now try to call the closure, first it will check if all the 
> captured objects are still available or not, if not the whole closure in this 
> case will simply become nil and won’t execute. In case of unowned closures it 
> will trap. Furthermore it will support the general meaning of weak/unowned 
> and will not increase the reference counter for *captured objects*.
> 
> As you have already noticed, in this case the convention is slightly 
> different because we must carry the behavior directly with the type.
> 
> func subscribe(onNext: weak ((Swift.E) -> Void)?)
> 
> If the way of my thinking is correct this idea _could maybe_ fade out the 
> very common [weak self] in guard let strongSelf = self … pattern. 
> 
> I personally cannot tell all the technical difficulties this idea might have, 
> but that’s what the evolution list is for, to collaboratively flesh out the 
> ideas if they are worth it.
> 
> If something like this could be possible it’s probably worth noting that we 
> might also be able to introduce something like @autoclosure(weak/unowned) to 
> Swift for consistency.
> 
> 
> 
> 
> -- 
> Adrian Zubarev
> Sent with Airmail
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-evolution 
> 

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


Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Hi, Riley!

I think that's a great idea! We can merge the second part of my proposal (the 
`indirect init`) into your one and refine and consolidate the prerequisite 
proposal (about returning from `init` and possibly in-place member 
initializers) and bunch them up into a proposal cluster (the way swift coders 
did).
Feel free to tear out any chunks from my proposal, while I think about a more 
in-depth rationale about revamping initialization syntax. 

> On Jun 10, 2017, at 8:36 PM, Riley Testut  wrote:
> 
> Hi Gor 
> 
> I’m very much in fan of a unified initialization syntax. I submitted my own 
> proposal for factory initializers a while back, but since it wasn’t a focus 
> of Swift 3 or 4 I haven’t followed up on it recently. In the time since last 
> working on it, I came to my own conclusion that rather than focusing on 
> factory initialization, the overall initialization process should be 
> simplified, which I’m glad to see someone else has realized as well :-)
> 
> Here’s my proposal for reference: 
> https://github.com/apple/swift-evolution/pull/247/commits/58b5a93b322aae998eb40574dee15fe54323de2e
>  
> 
>  Originally I used the “factory” keyword, but I think your “indirect” keyword 
> may be a better fit (since it has precedent in the language and is not 
> limited to “just” being about factory initialization). To divide your 
> proposal up into smaller pieces for review, maybe we could update my proposal 
> to use your indirect keyword, and then start a separate topic/proposal for 
> the remaining aspects of your proposal? I agree that splitting it into 
> smaller chunks may be better for the process.
> 
> Let me know what you think!
> 
> Riley
> 
> 
>> On Jun 10, 2017, at 3:33 AM, Gor Gyolchanyan via swift-evolution 
>> > wrote:
>> 
>>> 
>>> This is a very interesting read.
>>> 
>> 
>> Thanks you! I tried to make it as clear and detailed as possible.  
>> 
>>> 
>>> We did not discuss the 'indirect' idea at all on this list. Did you come up 
>>> with it just now? In any case, my suggestion as to moving forward would be 
>>> this:
>>> 
>> I was writing the proposal and was just about to write `factory init`, when 
>> it occurred to me: enums already have a keyword that does something very 
>> similar. It seemed to me that an initializer that doesn't initialize the 
>> instance in-place, but returns a completely separate instance from somewhere 
>> else, is kinda "indirectly" initializing the instance. Plus, the already 
>> established keyword and its semantic would reduce the learning curve for 
>> this new feature and separate it from a single specific use case (the 
>> "factory method" pattern).
>> 
>>> 
>>> - Do you feel that both halves of your draft (expanding `return` in 
>>> initializers, and `indirect` initializers) should absolutely be one 
>>> proposal, or can they be separated?
>>> 
>> I think the `return` can be easily implemented first, while opening up an 
>> opportunity to later implement `indirect init`. The reason why I unified 
>> them was that the `return` idea on its own has very limited merit and could 
>> the thought of as a low-priority cosmetic enhancement. I wouldn't want it to 
>> be viewed that way because the primary purpose of that idea is to enable 
>> `indirect init` (which Cocoa and Cocoa Touch developers would be very happy 
>> about). 
>> 
>>> 
>>> a) If they can be separated because each half has individual merit, then 
>>> these ideas may be more likely to succeed as separate proposals, as each 
>>> can be critiqued fully and judged independently as digestible units.
>>> 
>> 
>> Very good point. The challenge is to correctly separate them, without losing 
>> context in their respective proposals and without bleeding the proposals 
>> into each other.
>> 
>> 
>>> 
>> 
>>> b) If you intend to tackle all your ideas all at once, that's going to be a 
>>> much bigger change--in terms of review effort, likely bikeshedding, and 
>>> implementation effort. It'll probably be best to solicit initial feedback 
>>> on this list first about `indirect` initializers, even if just to 
>>> familiarize the community with the idea, before launching into a pitch of 
>>> the whole proposal.
>>> 
>> 
>> I'd never send a pull request to swift-evolution without thoroughly 
>> discussing it here. I just though, if I'm going to write a whole proposal 
>> with examples and motivation, it would be easier to demonstrate it and 
>> discuss in with the community If I just went ahead and wrote the whole thing 
>> and sent the link. This way it would be clearer to the reader and the 
>> discussed changes would be accurately reflected by the commits I'd make to 
>> my proposal.
>> 
>> Original Message
>> 
>>> On Jun 10, 2017, at 2:38 AM, Daryle Walker via swift-evolution 
>>> 

[swift-evolution] [Pitch] Introduction of `weak/unowned` closures

2017-06-10 Thread Adrian Zubarev via swift-evolution
Hello Evolution,

I’d like to pitch a new idea and see where it would go. Recently I tapped into 
a small trap and just now realized that even that non-escaping should have been 
the default for closures (SE–0103) there is an exception for that. Apparently 
generics don’t follow that rule and a closure like

Optional<() -> Void> or simply (() -> Void)?

is still escaping by default. But that was the half of the story yet. As we all 
know and “love” reference lists inside closures, methods don’t have any and we 
have to wrap method calls into a weak referenced closure

{ [weak self] in self.foo() }

to avoid strong reference cycles. Maybe you already guess it, I accidentally 
didn’t and tapped into the land of strong reference cycles yet again on my 
journey.

I’d like to pitch a new way, more like a new type behavior, for closures on how 
they could be used differently in order to avoid strong reference cycles but 
also providing the ability to use methods without any need to wrap them.

Here is a simple code snippet using RxSwift, which will recreate my issue:

import RxSwift

let test = PublishSubject()

class A {

let disposeBag = DisposeBag()

func foo() {
test.asObservable()
.subscribe(onNext: self.bar) // The issue is here
.disposed(by: self.disposeBag)
}

func bar() { print("works") }
}

let a = A()
a.foo()

test.onNext(()) // Testing if it works
test.onCompleted() // Some RxSwift stuff
In this case by passing directly the method self.bar we’re capturing self, 
which in this situation isn’t our intention at all. To avoid this issue we can 
simply wrap the method call into closure:

.subscribe(onNext: { [unowned self] in self.bar() })

(It’s safe to make it unowned because the dispose bag is a member of self.)

What if we had the ability for weak or unowned closures? By that I don’t mean 
weak/unowned references to the closures themselves, because they are also 
reference types, but an invalidation behavior for the whole closure based on 
the _captured_ references. For instance:

let closure1: weak (() -> Void)? = { self.doWhatever() }

let closure2: weak (() -> Void)? = self.doWhatever

If one would now try to call the closure, first it will check if all the 
captured objects are still available or not, if not the whole closure in this 
case will simply become nil and won’t execute. In case of unowned closures it 
will trap. Furthermore it will support the general meaning of weak/unowned and 
will not increase the reference counter for *captured objects*.

As you have already noticed, in this case the convention is slightly different 
because we must carry the behavior directly with the type.

func subscribe(onNext: weak ((Swift.E) -> Void)?)

If the way of my thinking is correct this idea _could maybe_ fade out the very 
common [weak self] in guard let strongSelf = self … pattern.

I personally cannot tell all the technical difficulties this idea might have, 
but that’s what the evolution list is for, to collaboratively flesh out the 
ideas if they are worth it.

If something like this could be possible it’s probably worth noting that we 
might also be able to introduce something like @autoclosure(weak/unowned) to 
Swift for consistency.



-- 
Adrian Zubarev
Sent with Airmail
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Riley Testut via swift-evolution
Hi Gor 

I’m very much in fan of a unified initialization syntax. I submitted my own 
proposal for factory initializers a while back, but since it wasn’t a focus of 
Swift 3 or 4 I haven’t followed up on it recently. In the time since last 
working on it, I came to my own conclusion that rather than focusing on factory 
initialization, the overall initialization process should be simplified, which 
I’m glad to see someone else has realized as well :-)

Here’s my proposal for reference: 
https://github.com/apple/swift-evolution/pull/247/commits/58b5a93b322aae998eb40574dee15fe54323de2e
 

 Originally I used the “factory” keyword, but I think your “indirect” keyword 
may be a better fit (since it has precedent in the language and is not limited 
to “just” being about factory initialization). To divide your proposal up into 
smaller pieces for review, maybe we could update my proposal to use your 
indirect keyword, and then start a separate topic/proposal for the remaining 
aspects of your proposal? I agree that splitting it into smaller chunks may be 
better for the process.

Let me know what you think!

Riley


> On Jun 10, 2017, at 3:33 AM, Gor Gyolchanyan via swift-evolution 
>  wrote:
> 
>> 
>> This is a very interesting read.
>> 
> 
> Thanks you! I tried to make it as clear and detailed as possible.  
> 
>> 
>> We did not discuss the 'indirect' idea at all on this list. Did you come up 
>> with it just now? In any case, my suggestion as to moving forward would be 
>> this:
>> 
> I was writing the proposal and was just about to write `factory init`, when 
> it occurred to me: enums already have a keyword that does something very 
> similar. It seemed to me that an initializer that doesn't initialize the 
> instance in-place, but returns a completely separate instance from somewhere 
> else, is kinda "indirectly" initializing the instance. Plus, the already 
> established keyword and its semantic would reduce the learning curve for this 
> new feature and separate it from a single specific use case (the "factory 
> method" pattern).
> 
>> 
>> - Do you feel that both halves of your draft (expanding `return` in 
>> initializers, and `indirect` initializers) should absolutely be one 
>> proposal, or can they be separated?
>> 
> I think the `return` can be easily implemented first, while opening up an 
> opportunity to later implement `indirect init`. The reason why I unified them 
> was that the `return` idea on its own has very limited merit and could the 
> thought of as a low-priority cosmetic enhancement. I wouldn't want it to be 
> viewed that way because the primary purpose of that idea is to enable 
> `indirect init` (which Cocoa and Cocoa Touch developers would be very happy 
> about). 
> 
>> 
>> a) If they can be separated because each half has individual merit, then 
>> these ideas may be more likely to succeed as separate proposals, as each can 
>> be critiqued fully and judged independently as digestible units.
>> 
> 
> Very good point. The challenge is to correctly separate them, without losing 
> context in their respective proposals and without bleeding the proposals into 
> each other.
> 
> 
>> 
> 
>> b) If you intend to tackle all your ideas all at once, that's going to be a 
>> much bigger change--in terms of review effort, likely bikeshedding, and 
>> implementation effort. It'll probably be best to solicit initial feedback on 
>> this list first about `indirect` initializers, even if just to familiarize 
>> the community with the idea, before launching into a pitch of the whole 
>> proposal.
>> 
> 
> I'd never send a pull request to swift-evolution without thoroughly 
> discussing it here. I just though, if I'm going to write a whole proposal 
> with examples and motivation, it would be easier to demonstrate it and 
> discuss in with the community If I just went ahead and wrote the whole thing 
> and sent the link. This way it would be clearer to the reader and the 
> discussed changes would be accurately reflected by the commits I'd make to my 
> proposal.
> 
> Original Message
> 
>> On Jun 10, 2017, at 2:38 AM, Daryle Walker via swift-evolution 
>> > wrote:
>> 
>> On Fri, Jun 9, 2017 at 5:32 PM, Gor Gyolchanyan > > wrote:
>> Forked swift-evolution, created a draft proposal:
>> 
>> https://github.com/technogen-gg/swift-evolution/blob/master/proposals/-uniform-initialization.md
>>  
>> 
>> 
>> This is my first proposal, so I might have missed something or composed it 
>> wrong, so please feel free to comment, fork and send pull requests. 
>> 
>> 
>> This is a very interesting read. We did not discuss the 'indirect' idea at 
>> all on this list. 

Re: [swift-evolution] [Pitch] #error

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Love it! Except I'd add `warning` as well.

> On Jun 10, 2017, at 8:15 PM, Daryle Walker via swift-evolution 
>  wrote:
> 
> Unconditional Error Messages
> Proposal: SE- 
> Authors: Daryle Walker , Author 2 
> 
> Review Manager: TBD
> Status: Awaiting review
> During the review process, add the following fields as needed:
> 
> Decision Notes: Rationale 
> , Additional Commentary 
> 
> Bugs: SR- , SR- 
> 
> Previous Revision: 1 
> 
> Previous Proposal: SE- 
> Introduction
> This proposal adds the #error directive, which unconditionally posts a 
> compile-time error.
> 
> Swift-evolution thread: Discussion thread topic for that proposal 
> 
> Motivation
> A conditional compilation block permits branches of code based on the 
> compilation conditions.
> 
> #if compilation condition 1
> // statements to compile if compilation condition 1 is true
> #elseif compilation condition 2
> // statements to compile if compilation condition 2 is true
> #else
> // statements to compile if both compilation conditions are false
> #endif
> A block lets at most one of its branches to be incorporated into the compiled 
> module. But compilation always occurs; there is no scenario to flag 
> conditions that should never allow compiling.
> 
> When suspending work on a source file for a while, marking where you ended 
> work with an unconditional error message would let the compiler remind you 
> where you left off.
> 
> Proposed solution
> The solution is to add a new compiler control statement, one that posts a 
> fatal diagnostic during compilation. It can include a message to aid the user 
> on how to change their code.
> 
> It's called #error, after the C preprocessor directive that has the same 
> effects.
> 
> For example, instead of checking API compatibility at run-time:
> 
> guard #available(tvOS 1.0, *) else {
> fatalError("We need a TV.")
> }
> 
> // Do what we're supposed to do
> We can move the check to compile-time:
> 
> #if os(tvOS)
> // Do what we're supposed to do
> #else
> #error("We need a TV.")
> #endif
> Detailed design
> Add to the "Grammar of a Compiler Control Statement":
> 
> compiler-control-statement → error-directive-statement­
> Add a new section "Grammar of a Error Directive Statement":
> 
> error-directive-statement → #error ( static-string-literal )
> The semantics of an error directive statement are: when such a statement is 
> encountered during translation, and it is not in an inactive compilation 
> block branch, compilation is aborted and the directive's string is included 
> in the diagnostic of the directive's source line.
> 
> Source compatibility
> This proposal should cause no problems with source compatibility. Relative to 
> the current grammar, there is an addition of one token: #error. Since 
> #-leading tokens are illegal except for the explicitly defined ones, there is 
> no possibly of token overlap in legacy code.
> 
> Effect on ABI stability
> Since the domain of this proposal is all in the compilation phase of creating 
> object code, there is no effect on ABI stability.
> 
> Effect on API resilience
> The domain of this proposal, controlling whether translation completes, does 
> not affect any API.
> 
> Alternatives considered
> The alternative is to do nothing. This would mean any checks would stay being 
> delayed into run-time, and calling fatalError or similar functions to avoid 
> implementing uncovered compilation cases.
> 
> The original C syntax left open tokens as the message after the #error token. 
> I decided to enclose the message as a string to ease parsing.
> 
> Future directions
> The original idea for this proposal was a distraction while bringing an 
> adaptation of C++'s static_assert, as defined in its proposal 
> . The 
> static_assert is a condition-checking mechanic between assert and #error; 
> Swift already has the former and this proposal would bring the latter. 
> There'd still be no equivalent for static_assert. Another proposal for 
> non-environment compile-time expressions and their use in generic where 
> clauses would relieve most of need for static_assert, but there needs to be 
> either a new construct a declaration-level version or #if/#elseif need to be 
> allowed to access non-environment compile-time expressions.
> 
> Acknowledgements
> How to Use the C Preprocessor's #error Directive 
> 
>  by Nigel Jones
> 
> — 
> Daryle Walker
> Mac, Internet, and Video Game 

[swift-evolution] [Pitch] #error

2017-06-10 Thread Daryle Walker via swift-evolution
Unconditional Error Messages
Proposal: SE- 
Authors: Daryle Walker , Author 2 

Review Manager: TBD
Status: Awaiting review
During the review process, add the following fields as needed:

Decision Notes: Rationale , 
Additional Commentary 
Bugs: SR- , SR- 

Previous Revision: 1 

Previous Proposal: SE- 
Introduction
This proposal adds the #error directive, which unconditionally posts a 
compile-time error.

Swift-evolution thread: Discussion thread topic for that proposal 

Motivation
A conditional compilation block permits branches of code based on the 
compilation conditions.

#if compilation condition 1
// statements to compile if compilation condition 1 is true
#elseif compilation condition 2
// statements to compile if compilation condition 2 is true
#else
// statements to compile if both compilation conditions are false
#endif
A block lets at most one of its branches to be incorporated into the compiled 
module. But compilation always occurs; there is no scenario to flag conditions 
that should never allow compiling.

When suspending work on a source file for a while, marking where you ended work 
with an unconditional error message would let the compiler remind you where you 
left off.

Proposed solution
The solution is to add a new compiler control statement, one that posts a fatal 
diagnostic during compilation. It can include a message to aid the user on how 
to change their code.

It's called #error, after the C preprocessor directive that has the same 
effects.

For example, instead of checking API compatibility at run-time:

guard #available(tvOS 1.0, *) else {
fatalError("We need a TV.")
}

// Do what we're supposed to do
We can move the check to compile-time:

#if os(tvOS)
// Do what we're supposed to do
#else
#error("We need a TV.")
#endif
Detailed design
Add to the "Grammar of a Compiler Control Statement":

compiler-control-statement → error-directive-statement­
Add a new section "Grammar of a Error Directive Statement":

error-directive-statement → #error ( static-string-literal )
The semantics of an error directive statement are: when such a statement is 
encountered during translation, and it is not in an inactive compilation block 
branch, compilation is aborted and the directive's string is included in the 
diagnostic of the directive's source line.

Source compatibility
This proposal should cause no problems with source compatibility. Relative to 
the current grammar, there is an addition of one token: #error. Since #-leading 
tokens are illegal except for the explicitly defined ones, there is no possibly 
of token overlap in legacy code.

Effect on ABI stability
Since the domain of this proposal is all in the compilation phase of creating 
object code, there is no effect on ABI stability.

Effect on API resilience
The domain of this proposal, controlling whether translation completes, does 
not affect any API.

Alternatives considered
The alternative is to do nothing. This would mean any checks would stay being 
delayed into run-time, and calling fatalError or similar functions to avoid 
implementing uncovered compilation cases.

The original C syntax left open tokens as the message after the #error token. I 
decided to enclose the message as a string to ease parsing.

Future directions
The original idea for this proposal was a distraction while bringing an 
adaptation of C++'s static_assert, as defined in its proposal 
. The 
static_assert is a condition-checking mechanic between assert and #error; Swift 
already has the former and this proposal would bring the latter. There'd still 
be no equivalent for static_assert. Another proposal for non-environment 
compile-time expressions and their use in generic where clauses would relieve 
most of need for static_assert, but there needs to be either a new construct a 
declaration-level version or #if/#elseif need to be allowed to access 
non-environment compile-time expressions.

Acknowledgements
How to Use the C Preprocessor's #error Directive 
 
by Nigel Jones

— 
Daryle Walker
Mac, Internet, and Video Game Junkie
darylew AT mac DOT com 

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


[swift-evolution] Type Safe Key-Value Construct

2017-06-10 Thread David Moore via swift-evolution
  
  


  
  
>   
> 
>  Hello swift-evolution,  
>
>   
> There are clearly weaknesses with obtaining values from a given dictionary in 
> swift. Most notably, if we have a [String: Any] dictionary, how is one 
> supposed to set/get a value with type safety? The following concept addresses 
> this very issue.
>   
>
>   
> I regularly use a self-constructed structure with static constants embedded 
> within it, the structure enables a type safe implementation of keys and 
> values (especially Dictionary applications). I will include a code snippet 
> later on in this message, but I would specifically like to describe the 
> benefits of a type safe key and value system, and how it would benefit the 
> language.   
>   
>
>   
> When using dictionaries in Swift, one often finds themselves needing to use 
> more general key and value types (e.g. [String: Any]). Unfortunately, when a 
> Dictionary uses a general type, rather than one with more type safety and 
> compile time checks, many issues can arise from such a use case.
>   
>
>   
> The solution, in my opinion, is to use a pairing struct which can be used to 
> create constant type-safe-enforcing structures. Additionally, said struct 
> could have the ability to transform values of one type to that of another. 
> Please see the code snippet below for more information regarding the 
> implementation.
>   
>
>   
> >   
> >   
> >  struct  Bar {
> >   
> >   var  str:  String
> >   
> >  }
> >   
> >   
> >   
> >   var  foo = [String:  Any]()
> >   
> >   foo["bar"] =   Bar(str:  "Hello, world.")
> >   
> >   
> >   
> >  // We are optionally casting this value of `Any` to `Bar`, but it's 
> > strongly typed, so there are clearly drawbacks.
> >   
> >   if   let  bar =  foo["bar"]  as?  Bar  {
> >   
> >  bar.str
> >   
> >  }
> >   
> >   
> >   
> >  // What if we use a `KeyValuePair`?
> >   
> >   let  barPair =  KeyValuePair(key:  "bar")
> >   
> >   barPair.addValue(Bar(str:  "This is better."), to:  )
> >   
> >   
> >   
> >  // Now look how easy (and safe) it is to get the value.
> >   
> >   let  bar =  barPair.value(from:  foo)
> >   
> >   
>   
>   
> I have already implemented the underlying structure for the above example 
> usage. Also, there are other use cases that are not highlighted here, such as 
> built in value transformation.   
>   
>
>   
> Let me know if anyone else agrees that this is a type safe solution for 
> generalized dictionaries, or if think there are other uses for it. I also 
> have all the code for the struct KeyValuePair, if anyone wants to see how it 
> works, but it’s quite lightweight.
>   
>
>   
> Thank you,
>   
>   
>   
>   
>   
>
>   
>
>   
>
>   David Moore   /   Owner / Chief Executive Officer   
>da...@mooredev.ca (mailto:da...@mooredev.ca)   /   (705) 845-6057
>
>   
>
>   Moore Development   
>https://www.mooredev.ca
>
>   
>
>   
>
>   
>
>   
>
>   
>
>   
>
>   
>   
>   
>   
  
  
   ___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Pitch: Allow @objc for all property declarations regardless of type

2017-06-10 Thread Charles Srstka via swift-evolution
INTRODUCTION:

This pitch proposes to allow the @objc keyword on all property declarations, 
even ones whose type cannot be represented in Objective-C.

MOTIVATION:

You’re thinking, “But that’s crazy. Why would you ever want to do that?” But 
hear me out:

- In Swift 4, barring cases where it’s required for technical reasons, 
properties are exposed to Objective-C only if there’s an actual @objc keyword 
present. This keyword represents a clear statement of intent that this protocol 
is meant to be visible to Objective-C, and means that expanding the scope of 
the @objc keyword will not increase code size anywhere other than where a 
deliberate decision has been made to do so.

- Since Swift 3, all Swift types are in fact bridgeable to Objective-C, and an 
‘Any’ is bridged to an ‘id’.

- While it’s true that Objective-C will generally get an opaque object that it 
won’t know what to do with, that doesn’t mean that there aren’t cases where 
this can still be useful, such as:

- Value transformers. Even if a type is completely opaque to Objective-C, that 
doesn’t mean a value transformer can’t convert it into something that 
Objective-C can use. There are some quite useful general-purpose value 
transformers that could be written for this task, such as:

class CustomStringConvertibleValueTransformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass { return 
NSString.self }
override class func allowsReverseTransformation() -> Bool { return false }

override func transformedValue(_ value: Any?) -> Any? {
return (value as? CustomStringConvertible)?.description
}
}

With this value transformer, an enum like this one from the Swift manual could 
be exposed to Objective-C and bound to a UI element in Interface Builder, 
resulting in a meaningful value being shown in the UI:

enum Suit: CustomStringConvertible {
case spades, hearts, diamonds, clubs
var description: String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
}

Once we have generalized existentials, we could write this value transformer as 
well, which would be able to handle all Swift enums backed by 
ObjC-representable types without any special hacks:

class RawRepresentableValueTransformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass { return 
AnyObject.self }
override class func allowsReverseTransformation() -> Bool { return false }

override func transformedValue(_ value: Any?) -> Any? {
return (value as? RawRepresentable)?.rawValue
}
}

- KVO dependencies. Even without a value transformer, a property of a 
non-ObjC-representable type may be a dependency of other properties which *are* 
ObjC-representable, as in this example:

class PlayingCard: NSObject {
@objc dynamic var suit: Suit // currently an error

init(suit: Suit) {
self.suit = suit
super.init()
}

@objc private static let keyPathsForValuesAffectingSuitName: Set = 
[#keyPath(suit)]
@objc var suitName: String { return self.suit.description }
}

Although the ‘suit’ property is not representable in Objective-C, the 
‘suitName’ property is, and it would behoove us to allow it to be updated when 
‘suit’ changes. Currently, we have to resort to various hacks to accomplish 
this. One can manually send the KVO notifications on the original property 
instead of near the dependent ones, which can be error-prone:

class ErrorPronePlayingCard: NSObject {
var suit: Suit {
willSet { self.willChangeValue(for: \.suitName) }
didSet { self.didChangeValue(for: \.suitName) }
}

init(suit: Suit) {
self.suit = suit
super.init()
}

@objc var suitName: String { return self.suit.description }
}

Formerly, one could simply use arbitrary strings as key paths, which was ugly 
since it required a separate override of value(forKey:) to avoid exceptions if 
someone actually tried to acquire a value using the key. Also, it doesn’t seem 
to work anymore in Swift 4, since the will/didChangeValue methods now expect a 
KeyPath object instead of a String:

class DontWorkNoMorePlayingCard: NSObject {
var suit: Suit {
willSet { self.willChangeValue(for: "suit") } // error: this requires a 
KeyPath now
didSet { self.didChangeValue(for: "suit") }
}

override func value(forKey key: String) -> Any? {
switch key {
case "suit":
return self.suit
default:
return super.value(forKey: key)
}
}

init(suit: Suit) {
self.suit = suit
super.init()
}

@objc private static let keyPathsForValuesAffectingSuitName: Set = 
["suit"]
@objc var suitName: String { return self.suit.description }
}

One can ugly up 

Re: [swift-evolution] Introduction of OrderedSet

2017-06-10 Thread Tony Parker via swift-evolution
This is still something I want to do, but I suspect it will require some 
coordination work with the NSOrderedSet ref type in Foundation.

Also, as Doug says, there is a larger question too of how we make source 
breaking changes like this in Swift 5 (I think we’re probably out of runway for 
Swift 4 at this point).

We would want to bridge this in from the SDK, but if it follows the pattern of 
our value types, we need to make API changes from the ref type to make it fit 
in correctly with Swift-only concepts like the Collection protocols.

- Tony

> On Jun 9, 2017, at 4:28 PM, Douglas Gregor via swift-evolution 
>  wrote:
> 
>> 
>> On Jun 9, 2017, at 10:19 AM, Xiaodi Wu via swift-evolution 
>> > wrote:
>> 
>> Let me try to redirect this conversation, if I may.
>> 
>> As far as I can tell, SE-0069 states plainly that the plan of record is to 
>> offer a value type called OrderedSet in Foundation, but resources to design 
>> and implement were not then available.
>> 
>> So, little point in having a vote as to whether one is in favor of 
>> OrderedSet or not. In my view, the questions to be answered are:
>> 
>> For the core team–
>> 
>> * Is it still the plan to offer value types postponed from SE-0069 as a 
>> future addition to Foundation?
> 
> *I* think it’s still a good idea, and I suspect that others on the core team 
> will agree.
> 
>> * If so, is that a priority in the Swift 5 timeframe, and how can the 
>> community help to bring about this addition?
> 
> I wouldn’t consider it a “priority”, in the sense that I can’t imagine 
> anything in Swift 5 that would absolutely require us to introduce this 
> functionality in that time frame. It’s a bit of a nice-to-have-at-any-point, 
> noting of course that bridging NSOrderedSet in existing APIs is a nontrivial 
> source-breaking change.
> 
> Having a proposed API and implementation on hand makes it easier to add this 
> functionality, of course.
> 
>> If not, for the whole community–
>> 
>> * Is it wise to implement such a type in the standard library? Should we 
>> simply bring over the native implementation from Swift Package Manager? What 
>> are the implications for bridging?
> 
> Obviously, we’d want an efficient copy-on-write, native implementation; the 
> Swift Package Manager implementation is a bit more bare-bones than we’d want: 
> absolute performance matters, so having a separate Set + Array in the struct 
> probably isn’t good enough. Bridging performance matters, so we’d probably 
> want the one-pointer representation like array uses where the pointer can be 
> vended directly to Objective-C.
> 
>   - Doug
> 
>> On Fri, Jun 9, 2017 at 11:38 Remy Demarest via swift-evolution 
>> > wrote:
>> +1 for ordered set and dictionary, and please add ordered dictionary in ObjC 
>> as well.
>> 
>> Envoyé de mon iPhone
>> 
>> Le 9 juin 2017 à 03:11, Robert Bennett via swift-evolution 
>> > a écrit :
>> 
>>> +1, and would also like to see OrderedDictionary as well.
>>> 
>>> On Jun 9, 2017, at 12:50 AM, Jeff Kelley via swift-evolution 
>>> > wrote:
>>> 
 I would be in favor of it; there have been a few times (including Core 
 Data, as you mentioned) where I would have used it had it been available.
 
 
 Jeff Kelley
 
 slauncha...@gmail.com  | @SlaunchaMan 
  | jeffkelley.org 
> On Jun 7, 2017, at 2:10 PM, Maik Koslowski via swift-evolution 
> > wrote:
> 
> Hello,
> 
> in the past there have been a few requests for an OrderedSet 
> implementation in Swift. In the proposal 
> https://github.com/apple/swift-evolution/blob/master/proposals/0069-swift-mutability-for-foundation.md
>  
> 
>  was mentioned that the OrderedSet will be considered for the feature.
> 
> However, since then there were a few discussions on OrderedSet but it 
> doesn’t get much attention and there wasn’t any comment about it from the 
> swift team.
> 
> I want to bring up some points, why an OrderedSet is needed in the base 
> library.
> 
> 1. CoreData is probably the most obvious place where people would use an 
> ordered set. Especially when working with large amounts of data, 
> presorting can save a lot of time and battery life. If a bridgeable 
> ordered set was part of the standard library we could use a ordered set 
> in swift without having to use the NSOrderedSet from objective c. Which 
> would be pretty nice in my opinion. Even 

Re: [swift-evolution] History and future of Swift's parentheses

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
You can kinda do this already:

func foo(_ parameter: inout ParameterType) {
var shortcut: TheType {
get {
return parameter.very.very.long.and.tedious.inout.member
}
set {
parameter.very.very.long.and.tedious.inout.member = 
newValue
}
}
// shortcut is of type `inout TypeType`
}

This is exactly what I imagine the compiler generating when I write this in a 
hypothetical Swift:

func foo(_ parameter: inout ParameterType) {
var shortcut: inout TheType = 
parameter.very.very.long.and.tedious.inout.member
}

Or, using type inference:

func foo(_ parameter: inout ParameterType) {
var shortcut: inout = parameter.very.very.long.and.tedious.inout.member
}

> On Jun 10, 2017, at 8:25 AM, John McCall  wrote:
> 
> 
>> On Jun 9, 2017, at 2:42 PM, Gor Gyolchanyan via swift-evolution 
>>  wrote:
>> 
>> My answer to `inout` is to promote it to a full-fledged "storage class" (in 
>> C terminology) and allow normal variables to be `inout`.
>> This would immediately solve the problems with `inout` being a magical thing 
>> in functions, as well as a convenient way of storing "references" (in C++ 
>> terminology) to potentially huge inout expressions, not to mention returning 
>> an inout from a function, effectively spreading the getter-setter 
>> awesomeness to everything else besides properties and subscripts.
> 
> C++ implements this idea by being utterly unsafe; Rust implements it by 
> introducing entire new dimensions of language complexity.  Are you proposing 
> one of these in particular, or do you have your own concept?
> 
> John.

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


Re: [swift-evolution] History and future of Swift's parentheses

2017-06-10 Thread T.J. Usiyan via swift-evolution
I vote language complexity in the form of hygienic macros.

/me slinks away

On Sat, Jun 10, 2017 at 1:25 AM, John McCall via swift-evolution <
swift-evolution@swift.org> wrote:

>
> > On Jun 9, 2017, at 2:42 PM, Gor Gyolchanyan via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > My answer to `inout` is to promote it to a full-fledged "storage class"
> (in C terminology) and allow normal variables to be `inout`.
> > This would immediately solve the problems with `inout` being a magical
> thing in functions, as well as a convenient way of storing "references" (in
> C++ terminology) to potentially huge inout expressions, not to mention
> returning an inout from a function, effectively spreading the getter-setter
> awesomeness to everything else besides properties and subscripts.
>
> C++ implements this idea by being utterly unsafe; Rust implements it by
> introducing entire new dimensions of language complexity.  Are you
> proposing one of these in particular, or do you have your own concept?
>
> 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] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Judging by the fact that the error says something like "missing `while`" and 
"use `repeat`instead", it looks like a bug in the parser, where it goes with 
the `do-while` to `repeat-while` transition error before checking for other 
possible constructs like `do { }`.

> On Jun 10, 2017, at 4:30 PM, Xiaodi Wu  wrote:
> 
> Well, IMO, if that change was intentional, it’s the original change that 
> warrants a full-fledged proposal. Without it, I think it’d be justified to 
> call this a regression and file a bug!
> On Sat, Jun 10, 2017 at 09:29 Gor Gyolchanyan  > wrote:
> Yeah. So, what's the official process for these kinds of things? I imagine it 
> would warrant a full-fledged proposal, would it?
> 
> 
>> On Jun 10, 2017, at 4:26 PM, Xiaodi Wu > > wrote:
>> 
>> I did not realize that change occurred with `do {}`! That seems like it 
>> should be a regression, given that previously there was explicitly a fix-it 
>> to rewrite naked `{}` to `do {}`.
>> On Sat, Jun 10, 2017 at 09:06 Gor Gyolchanyan > > wrote:
>> Yeah, that's why I mentioned a big **if** at the end. I love the `do { }` 
>> construct or variable isolation purposes and logical grouping, but 
>> unfortunately, Swift 4 has made it a lot uglier, by making it an error in 
>> its current form:
>> 
>> do {
>>  let a = "123"
>>  print(a)
>> } // error: missing `while`, also use `repeat` instead
>> 
>> The workaround is to do this:
>> 
>> do {
>>  let a = "123"
>>  print(a)
>> };
>> 
>> It might seem like a little change, but this really really bugs me for some 
>> reason. I always felt like semicolons in Swift should never be mandatory and 
>> should only be used for writing multiple statements on the same line.
>> 
>> Overall, I agree that this isn't a big enough reason to change the syntax 
>> for. Let's just make the `do { }` great again instead.
>> 
>> 
>>> On Jun 10, 2017, at 3:33 PM, Xiaodi Wu >> > wrote:
>>> 
>>> _Every_ addition to the basic syntax of the language is, by definition, 
>>> high cost. The bar for additions to the standard library is already very 
>>> high; the bar for additions to control flow syntax would be extraordinarily 
>>> high.
>>> 
>>> The proposed use case here is far from the original topic of repeat {} 
>>> while, which is unique because the condition lexically follows the loop.
>>> 
>>> For those loops in Swift where it is possible to declare variables in the 
>>> condition, these live in a magical middle scope that is intuitive to use 
>>> but also an exception to the rule of thumb that scopes are surrounded by 
>>> braces. As I wrote earlier, it is possible to manually create an analogous 
>>> scope by surrounding any loop with do {}. Any addition to the language 
>>> would have to be vastly superior to this currently possible alternative, 
>>> and I seriously doubt it is possible to invent such a thing because 
>>> anything shorter than the four letters in “do {}” would also obscure the 
>>> existence of the middle scope being created.
>>> 
>>> 
>>> On Sat, Jun 10, 2017 at 08:05 Goffredo Marocchi via swift-evolution 
>>> > wrote:
>>> If it is low cost and people do not come up with regressions/high cost + 
>>> negative impact scenarios then I would say go full steam ahead. It does 
>>> address an annoying scenario.
>>> 
>>> Sent from my iPhone
>>> 
>>> On 10 Jun 2017, at 12:04, Gor Gyolchanyan >> > wrote:
>>> 
 Not much, I think. The `where` clause already exists, conditional `let` 
 and `var` binding already exists. It'd take loosening up conditional 
 binding rules a bit and expanding the lexical structure to include `let` 
 and `var` bindings in `repeat`.
 
> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi  > wrote:
> 
> Quite interesting :), what impact would it have on the compiler?
> 
> Sent from my iPhone
> 
> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution 
> > wrote:
> 
>> I think a better way of achieving this would be to use the already 
>> existing `where` keyword in loops. The way it works right now is as 
>> follows:
>> 
>> let many = [1, 2, 3, 4, 5]
>> for each in many where each % 2 == 0 {
>>  print("found an even number: \(each)")
>> }
>> 
>> Unfortunately, unlike all other conditional scopes, `where` does not 
>> allow `let` and `var` bindings in it, so I'd suggest we add ability to 
>> do that:
>> 
>> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
>> for each in many where let number = each {
>>  

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Xiaodi Wu via swift-evolution
Well, IMO, if that change was intentional, it’s the original change that
warrants a full-fledged proposal. Without it, I think it’d be justified to
call this a regression and file a bug!
On Sat, Jun 10, 2017 at 09:29 Gor Gyolchanyan  wrote:

> Yeah. So, what's the official process for these kinds of things? I imagine
> it would warrant a full-fledged proposal, would it?
>
>
> On Jun 10, 2017, at 4:26 PM, Xiaodi Wu  wrote:
>
> I did not realize that change occurred with `do {}`! That seems like it
> should be a regression, given that previously there was explicitly a fix-it
> to rewrite naked `{}` to `do {}`.
> On Sat, Jun 10, 2017 at 09:06 Gor Gyolchanyan  wrote:
>
>> Yeah, that's why I mentioned a big **if** at the end. I love the `do { }`
>> construct or variable isolation purposes and logical grouping, but
>> unfortunately, Swift 4 has made it a lot uglier, by making it an error in
>> its current form:
>>
>> do {
>> let a = "123"
>> print(a)
>> } // error: missing `while`, also use `repeat` instead
>>
>> The workaround is to do this:
>>
>> do {
>> let a = "123"
>> print(a)
>> };
>>
>> It might seem like a little change, but this really really bugs me for
>> some reason. I always felt like semicolons in Swift should never be
>> mandatory and should only be used for writing multiple statements on the
>> same line.
>>
>> Overall, I agree that this isn't a big enough reason to change the syntax
>> for. Let's just make the `do { }` great again instead.
>>
>>
>> On Jun 10, 2017, at 3:33 PM, Xiaodi Wu  wrote:
>>
>> _Every_ addition to the basic syntax of the language is, by definition,
>> high cost. The bar for additions to the standard library is already very
>> high; the bar for additions to control flow syntax would be extraordinarily
>> high.
>>
>> The proposed use case here is far from the original topic of repeat {}
>> while, which is unique because the condition lexically follows the loop.
>>
>> For those loops in Swift where it is possible to declare variables in the
>> condition, these live in a magical middle scope that is intuitive to use
>> but also an exception to the rule of thumb that scopes are surrounded by
>> braces. As I wrote earlier, it is possible to manually create an analogous
>> scope by surrounding any loop with do {}. Any addition to the language
>> would have to be vastly superior to this currently possible alternative,
>> and I seriously doubt it is possible to invent such a thing because
>> anything shorter than the four letters in “do {}” would also obscure the
>> existence of the middle scope being created.
>>
>>
>> On Sat, Jun 10, 2017 at 08:05 Goffredo Marocchi via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>>> If it is low cost and people do not come up with regressions/high cost +
>>> negative impact scenarios then I would say go full steam ahead. It does
>>> address an annoying scenario.
>>>
>>> Sent from my iPhone
>>>
>>> On 10 Jun 2017, at 12:04, Gor Gyolchanyan  wrote:
>>>
>>> Not much, I think. The `where` clause already exists, conditional `let`
>>> and `var` binding already exists. It'd take loosening up conditional
>>> binding rules a bit and expanding the lexical structure to include `let`
>>> and `var` bindings in `repeat`.
>>>
>>> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi 
>>> wrote:
>>>
>>> Quite interesting :), what impact would it have on the compiler?
>>>
>>> Sent from my iPhone
>>>
>>> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution <
>>> swift-evolution@swift.org> wrote:
>>>
>>> I think a better way of achieving this would be to use the already
>>> existing `where` keyword in loops. The way it works right now is as follows:
>>>
>>> let many = [1, 2, 3, 4, 5]
>>> for each in many where each % 2 == 0 {
>>> print("found an even number: \(each)")
>>> }
>>>
>>> Unfortunately, unlike all other conditional scopes, `where` does not
>>> allow `let` and `var` bindings in it, so I'd suggest we add ability to do
>>> that:
>>>
>>> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
>>> for each in many where let number = each {
>>> print("found a non-nil number: \(number)")
>>> }
>>>
>>> Or, more interestingly:
>>>
>>> for each in many where let number = each, number % 2 == 0 {
>>> print("found a non-nil even number: \(number)")
>>> }
>>>
>>> And in case of a while loop:
>>>
>>> var optional: Int? = 1
>>> while let nonoptional = optional {
>>> if nonoptional >= 10 {
>>> optional = nil
>>> }
>>> optional = nonoptional + 1
>>> }
>>>
>>> But this is only for optional unpacking, so another addition would be to
>>> allow any `let` and `var` bindings in conditional scopes without them
>>> contributing to the condition itself:
>>>
>>> while let a = 0, a < 10 {
>>> a += 1
>>> print(a)
>>> }
>>>
>>> And finally, allow these bindings in `repeat`:
>>>
>>> repeat let a = 0 {
>>> a += 1
>>> print(0)
>>> } while a < 10
>>>
>>> I 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Yeah. So, what's the official process for these kinds of things? I imagine it 
would warrant a full-fledged proposal, would it?

> On Jun 10, 2017, at 4:26 PM, Xiaodi Wu  wrote:
> 
> I did not realize that change occurred with `do {}`! That seems like it 
> should be a regression, given that previously there was explicitly a fix-it 
> to rewrite naked `{}` to `do {}`.
> On Sat, Jun 10, 2017 at 09:06 Gor Gyolchanyan  > wrote:
> Yeah, that's why I mentioned a big **if** at the end. I love the `do { }` 
> construct or variable isolation purposes and logical grouping, but 
> unfortunately, Swift 4 has made it a lot uglier, by making it an error in its 
> current form:
> 
> do {
>   let a = "123"
>   print(a)
> } // error: missing `while`, also use `repeat` instead
> 
> The workaround is to do this:
> 
> do {
>   let a = "123"
>   print(a)
> };
> 
> It might seem like a little change, but this really really bugs me for some 
> reason. I always felt like semicolons in Swift should never be mandatory and 
> should only be used for writing multiple statements on the same line.
> 
> Overall, I agree that this isn't a big enough reason to change the syntax 
> for. Let's just make the `do { }` great again instead.
> 
> 
>> On Jun 10, 2017, at 3:33 PM, Xiaodi Wu > > wrote:
>> 
>> _Every_ addition to the basic syntax of the language is, by definition, high 
>> cost. The bar for additions to the standard library is already very high; 
>> the bar for additions to control flow syntax would be extraordinarily high.
>> 
>> The proposed use case here is far from the original topic of repeat {} 
>> while, which is unique because the condition lexically follows the loop.
>> 
>> For those loops in Swift where it is possible to declare variables in the 
>> condition, these live in a magical middle scope that is intuitive to use but 
>> also an exception to the rule of thumb that scopes are surrounded by braces. 
>> As I wrote earlier, it is possible to manually create an analogous scope by 
>> surrounding any loop with do {}. Any addition to the language would have to 
>> be vastly superior to this currently possible alternative, and I seriously 
>> doubt it is possible to invent such a thing because anything shorter than 
>> the four letters in “do {}” would also obscure the existence of the middle 
>> scope being created.
>> 
>> 
>> On Sat, Jun 10, 2017 at 08:05 Goffredo Marocchi via swift-evolution 
>> > wrote:
>> If it is low cost and people do not come up with regressions/high cost + 
>> negative impact scenarios then I would say go full steam ahead. It does 
>> address an annoying scenario.
>> 
>> Sent from my iPhone
>> 
>> On 10 Jun 2017, at 12:04, Gor Gyolchanyan > > wrote:
>> 
>>> Not much, I think. The `where` clause already exists, conditional `let` and 
>>> `var` binding already exists. It'd take loosening up conditional binding 
>>> rules a bit and expanding the lexical structure to include `let` and `var` 
>>> bindings in `repeat`.
>>> 
 On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi > wrote:
 
 Quite interesting :), what impact would it have on the compiler?
 
 Sent from my iPhone
 
 On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution 
 > wrote:
 
> I think a better way of achieving this would be to use the already 
> existing `where` keyword in loops. The way it works right now is as 
> follows:
> 
> let many = [1, 2, 3, 4, 5]
> for each in many where each % 2 == 0 {
>   print("found an even number: \(each)")
> }
> 
> Unfortunately, unlike all other conditional scopes, `where` does not 
> allow `let` and `var` bindings in it, so I'd suggest we add ability to do 
> that:
> 
> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
> for each in many where let number = each {
>   print("found a non-nil number: \(number)")
> }
> 
> Or, more interestingly:
> 
> for each in many where let number = each, number % 2 == 0 {
>   print("found a non-nil even number: \(number)")
> }
> 
> And in case of a while loop:
> 
> var optional: Int? = 1
> while let nonoptional = optional {
>   if nonoptional >= 10 {
>   optional = nil
>   }
>   optional = nonoptional + 1
> }
> 
> But this is only for optional unpacking, so another addition would be to 
> allow any `let` and `var` bindings in conditional scopes without them 
> contributing to the condition itself:
> 
> while let a = 0, a < 10 {
>   a += 1
>   print(a)
> }
> 
> And finally, allow these bindings 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Xiaodi Wu via swift-evolution
I did not realize that change occurred with `do {}`! That seems like it
should be a regression, given that previously there was explicitly a fix-it
to rewrite naked `{}` to `do {}`.
On Sat, Jun 10, 2017 at 09:06 Gor Gyolchanyan  wrote:

> Yeah, that's why I mentioned a big **if** at the end. I love the `do { }`
> construct or variable isolation purposes and logical grouping, but
> unfortunately, Swift 4 has made it a lot uglier, by making it an error in
> its current form:
>
> do {
> let a = "123"
> print(a)
> } // error: missing `while`, also use `repeat` instead
>
> The workaround is to do this:
>
> do {
> let a = "123"
> print(a)
> };
>
> It might seem like a little change, but this really really bugs me for
> some reason. I always felt like semicolons in Swift should never be
> mandatory and should only be used for writing multiple statements on the
> same line.
>
> Overall, I agree that this isn't a big enough reason to change the syntax
> for. Let's just make the `do { }` great again instead.
>
>
> On Jun 10, 2017, at 3:33 PM, Xiaodi Wu  wrote:
>
> _Every_ addition to the basic syntax of the language is, by definition,
> high cost. The bar for additions to the standard library is already very
> high; the bar for additions to control flow syntax would be extraordinarily
> high.
>
> The proposed use case here is far from the original topic of repeat {}
> while, which is unique because the condition lexically follows the loop.
>
> For those loops in Swift where it is possible to declare variables in the
> condition, these live in a magical middle scope that is intuitive to use
> but also an exception to the rule of thumb that scopes are surrounded by
> braces. As I wrote earlier, it is possible to manually create an analogous
> scope by surrounding any loop with do {}. Any addition to the language
> would have to be vastly superior to this currently possible alternative,
> and I seriously doubt it is possible to invent such a thing because
> anything shorter than the four letters in “do {}” would also obscure the
> existence of the middle scope being created.
>
>
> On Sat, Jun 10, 2017 at 08:05 Goffredo Marocchi via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> If it is low cost and people do not come up with regressions/high cost +
>> negative impact scenarios then I would say go full steam ahead. It does
>> address an annoying scenario.
>>
>> Sent from my iPhone
>>
>> On 10 Jun 2017, at 12:04, Gor Gyolchanyan  wrote:
>>
>> Not much, I think. The `where` clause already exists, conditional `let`
>> and `var` binding already exists. It'd take loosening up conditional
>> binding rules a bit and expanding the lexical structure to include `let`
>> and `var` bindings in `repeat`.
>>
>> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi  wrote:
>>
>> Quite interesting :), what impact would it have on the compiler?
>>
>> Sent from my iPhone
>>
>> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> I think a better way of achieving this would be to use the already
>> existing `where` keyword in loops. The way it works right now is as follows:
>>
>> let many = [1, 2, 3, 4, 5]
>> for each in many where each % 2 == 0 {
>> print("found an even number: \(each)")
>> }
>>
>> Unfortunately, unlike all other conditional scopes, `where` does not
>> allow `let` and `var` bindings in it, so I'd suggest we add ability to do
>> that:
>>
>> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
>> for each in many where let number = each {
>> print("found a non-nil number: \(number)")
>> }
>>
>> Or, more interestingly:
>>
>> for each in many where let number = each, number % 2 == 0 {
>> print("found a non-nil even number: \(number)")
>> }
>>
>> And in case of a while loop:
>>
>> var optional: Int? = 1
>> while let nonoptional = optional {
>> if nonoptional >= 10 {
>> optional = nil
>> }
>> optional = nonoptional + 1
>> }
>>
>> But this is only for optional unpacking, so another addition would be to
>> allow any `let` and `var` bindings in conditional scopes without them
>> contributing to the condition itself:
>>
>> while let a = 0, a < 10 {
>> a += 1
>> print(a)
>> }
>>
>> And finally, allow these bindings in `repeat`:
>>
>> repeat let a = 0 {
>> a += 1
>> print(0)
>> } while a < 10
>>
>> I think **if** the core team would consider this a worthwhile addition,
>> this would be a less invasive and more intuitive way of achieving what you
>> want.
>>
>> On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution <
>> swift-evolution@swift.org> wrote:
>>
>> Not sure if my e-mail didn't go through or if discussion just fizzled
>> out; one other benefit if we ever move to a proper message board is we
>> might gain the ability to bump topics. Anyway, I'll resend my message just
>> in case:
>>
>>
>>
>> Just to add my thoughts, as I like the idea of adding the variables to
>> the start somehow, but 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Yeah, that's why I mentioned a big **if** at the end. I love the `do { }` 
construct or variable isolation purposes and logical grouping, but 
unfortunately, Swift 4 has made it a lot uglier, by making it an error in its 
current form:

do {
let a = "123"
print(a)
} // error: missing `while`, also use `repeat` instead

The workaround is to do this:

do {
let a = "123"
print(a)
};

It might seem like a little change, but this really really bugs me for some 
reason. I always felt like semicolons in Swift should never be mandatory and 
should only be used for writing multiple statements on the same line.

Overall, I agree that this isn't a big enough reason to change the syntax for. 
Let's just make the `do { }` great again instead.

> On Jun 10, 2017, at 3:33 PM, Xiaodi Wu  wrote:
> 
> _Every_ addition to the basic syntax of the language is, by definition, high 
> cost. The bar for additions to the standard library is already very high; the 
> bar for additions to control flow syntax would be extraordinarily high.
> 
> The proposed use case here is far from the original topic of repeat {} while, 
> which is unique because the condition lexically follows the loop.
> 
> For those loops in Swift where it is possible to declare variables in the 
> condition, these live in a magical middle scope that is intuitive to use but 
> also an exception to the rule of thumb that scopes are surrounded by braces. 
> As I wrote earlier, it is possible to manually create an analogous scope by 
> surrounding any loop with do {}. Any addition to the language would have to 
> be vastly superior to this currently possible alternative, and I seriously 
> doubt it is possible to invent such a thing because anything shorter than the 
> four letters in “do {}” would also obscure the existence of the middle scope 
> being created.
> 
> 
> On Sat, Jun 10, 2017 at 08:05 Goffredo Marocchi via swift-evolution 
> > wrote:
> If it is low cost and people do not come up with regressions/high cost + 
> negative impact scenarios then I would say go full steam ahead. It does 
> address an annoying scenario.
> 
> Sent from my iPhone
> 
> On 10 Jun 2017, at 12:04, Gor Gyolchanyan  > wrote:
> 
>> Not much, I think. The `where` clause already exists, conditional `let` and 
>> `var` binding already exists. It'd take loosening up conditional binding 
>> rules a bit and expanding the lexical structure to include `let` and `var` 
>> bindings in `repeat`.
>> 
>>> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi >> > wrote:
>>> 
>>> Quite interesting :), what impact would it have on the compiler?
>>> 
>>> Sent from my iPhone
>>> 
>>> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution 
>>> > wrote:
>>> 
 I think a better way of achieving this would be to use the already 
 existing `where` keyword in loops. The way it works right now is as 
 follows:
 
 let many = [1, 2, 3, 4, 5]
 for each in many where each % 2 == 0 {
print("found an even number: \(each)")
 }
 
 Unfortunately, unlike all other conditional scopes, `where` does not allow 
 `let` and `var` bindings in it, so I'd suggest we add ability to do that:
 
 let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
 for each in many where let number = each {
print("found a non-nil number: \(number)")
 }
 
 Or, more interestingly:
 
 for each in many where let number = each, number % 2 == 0 {
print("found a non-nil even number: \(number)")
 }
 
 And in case of a while loop:
 
 var optional: Int? = 1
 while let nonoptional = optional {
if nonoptional >= 10 {
optional = nil
}
optional = nonoptional + 1
 }
 
 But this is only for optional unpacking, so another addition would be to 
 allow any `let` and `var` bindings in conditional scopes without them 
 contributing to the condition itself:
 
 while let a = 0, a < 10 {
a += 1
print(a)
 }
 
 And finally, allow these bindings in `repeat`:
 
 repeat let a = 0 {
a += 1
print(0)
 } while a < 10
 
 I think **if** the core team would consider this a worthwhile addition, 
 this would be a less invasive and more intuitive way of achieving what you 
 want.
 
> On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution 
> > wrote:
> 
> Not sure if my e-mail didn't go through or if discussion just fizzled 
> out; one other benefit if we ever move to a proper message board is we 
> might gain the ability to bump topics. Anyway, I'll resend my message 
> 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Xiaodi Wu via swift-evolution
_Every_ addition to the basic syntax of the language is, by definition,
high cost. The bar for additions to the standard library is already very
high; the bar for additions to control flow syntax would be extraordinarily
high.

The proposed use case here is far from the original topic of repeat {}
while, which is unique because the condition lexically follows the loop.

For those loops in Swift where it is possible to declare variables in the
condition, these live in a magical middle scope that is intuitive to use
but also an exception to the rule of thumb that scopes are surrounded by
braces. As I wrote earlier, it is possible to manually create an analogous
scope by surrounding any loop with do {}. Any addition to the language
would have to be vastly superior to this currently possible alternative,
and I seriously doubt it is possible to invent such a thing because
anything shorter than the four letters in “do {}” would also obscure the
existence of the middle scope being created.


On Sat, Jun 10, 2017 at 08:05 Goffredo Marocchi via swift-evolution <
swift-evolution@swift.org> wrote:

> If it is low cost and people do not come up with regressions/high cost +
> negative impact scenarios then I would say go full steam ahead. It does
> address an annoying scenario.
>
> Sent from my iPhone
>
> On 10 Jun 2017, at 12:04, Gor Gyolchanyan  wrote:
>
> Not much, I think. The `where` clause already exists, conditional `let`
> and `var` binding already exists. It'd take loosening up conditional
> binding rules a bit and expanding the lexical structure to include `let`
> and `var` bindings in `repeat`.
>
> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi  wrote:
>
> Quite interesting :), what impact would it have on the compiler?
>
> Sent from my iPhone
>
> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> I think a better way of achieving this would be to use the already
> existing `where` keyword in loops. The way it works right now is as follows:
>
> let many = [1, 2, 3, 4, 5]
> for each in many where each % 2 == 0 {
> print("found an even number: \(each)")
> }
>
> Unfortunately, unlike all other conditional scopes, `where` does not allow
> `let` and `var` bindings in it, so I'd suggest we add ability to do that:
>
> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
> for each in many where let number = each {
> print("found a non-nil number: \(number)")
> }
>
> Or, more interestingly:
>
> for each in many where let number = each, number % 2 == 0 {
> print("found a non-nil even number: \(number)")
> }
>
> And in case of a while loop:
>
> var optional: Int? = 1
> while let nonoptional = optional {
> if nonoptional >= 10 {
> optional = nil
> }
> optional = nonoptional + 1
> }
>
> But this is only for optional unpacking, so another addition would be to
> allow any `let` and `var` bindings in conditional scopes without them
> contributing to the condition itself:
>
> while let a = 0, a < 10 {
> a += 1
> print(a)
> }
>
> And finally, allow these bindings in `repeat`:
>
> repeat let a = 0 {
> a += 1
> print(0)
> } while a < 10
>
> I think **if** the core team would consider this a worthwhile addition,
> this would be a less invasive and more intuitive way of achieving what you
> want.
>
> On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> Not sure if my e-mail didn't go through or if discussion just fizzled out;
> one other benefit if we ever move to a proper message board is we might
> gain the ability to bump topics. Anyway, I'll resend my message just in
> case:
>
>
>
> Just to add my thoughts, as I like the idea of adding the variables to the
> start somehow, but was wondering if might make sense to have a keyword such
> as "using", but allow it on all block statements, like-so:
>
> // Original use-case of repeat … while
> repeat using (var i = 0) {
> // Do something
> } while (i < 20)
>
> // for … in demonstrating combination of using and where
> for eachItem in theItems using (var i = 0) where (i < 20) {
> // Do something either until theItems run out or i reaches 20
> }
>
> // Standard while loop
> while let eachItem = it.next() using (var i = 0) where (i < 20) {
> // As above, but with an iterator and a while loop and conditional binding
> to also stop on nil
> }
>
> // Closure with its own captured variable
> let myClosure:(Int) -> Int = using (var i = 0) { i += 1; return i * $0 }
>
> // If statements as well
> if somethingIsTrue() using (var i = 0) where (i < 20) {
> // Do something
> }
>
> // Or even a do block; while it does nothing functionally new, I quite
> like it aesthetically
> do using (var i = 0) {
> // Do something
> }
>
> Unifying principle here is that anything created in the using clause
> belongs to the loop, conditional branch etc. only, but exists outside the
> block itself (thus persisting in the case of loops and closures). I quite
> like the possible 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Goffredo Marocchi via swift-evolution
If it is low cost and people do not come up with regressions/high cost + 
negative impact scenarios then I would say go full steam ahead. It does address 
an annoying scenario.

Sent from my iPhone

> On 10 Jun 2017, at 12:04, Gor Gyolchanyan  wrote:
> 
> Not much, I think. The `where` clause already exists, conditional `let` and 
> `var` binding already exists. It'd take loosening up conditional binding 
> rules a bit and expanding the lexical structure to include `let` and `var` 
> bindings in `repeat`.
> 
>> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi  wrote:
>> 
>> Quite interesting :), what impact would it have on the compiler?
>> 
>> Sent from my iPhone
>> 
>>> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution 
>>>  wrote:
>>> 
>>> I think a better way of achieving this would be to use the already existing 
>>> `where` keyword in loops. The way it works right now is as follows:
>>> 
>>> let many = [1, 2, 3, 4, 5]
>>> for each in many where each % 2 == 0 {
>>> print("found an even number: \(each)")
>>> }
>>> 
>>> Unfortunately, unlike all other conditional scopes, `where` does not allow 
>>> `let` and `var` bindings in it, so I'd suggest we add ability to do that:
>>> 
>>> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
>>> for each in many where let number = each {
>>> print("found a non-nil number: \(number)")
>>> }
>>> 
>>> Or, more interestingly:
>>> 
>>> for each in many where let number = each, number % 2 == 0 {
>>> print("found a non-nil even number: \(number)")
>>> }
>>> 
>>> And in case of a while loop:
>>> 
>>> var optional: Int? = 1
>>> while let nonoptional = optional {
>>> if nonoptional >= 10 {
>>> optional = nil
>>> }
>>> optional = nonoptional + 1
>>> }
>>> 
>>> But this is only for optional unpacking, so another addition would be to 
>>> allow any `let` and `var` bindings in conditional scopes without them 
>>> contributing to the condition itself:
>>> 
>>> while let a = 0, a < 10 {
>>> a += 1
>>> print(a)
>>> }
>>> 
>>> And finally, allow these bindings in `repeat`:
>>> 
>>> repeat let a = 0 {
>>> a += 1
>>> print(0)
>>> } while a < 10
>>> 
>>> I think **if** the core team would consider this a worthwhile addition, 
>>> this would be a less invasive and more intuitive way of achieving what you 
>>> want.
>>> 
 On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution 
  wrote:
 
 Not sure if my e-mail didn't go through or if discussion just fizzled out; 
 one other benefit if we ever move to a proper message board is we might 
 gain the ability to bump topics. Anyway, I'll resend my message just in 
 case:
 
 
 
 Just to add my thoughts, as I like the idea of adding the variables to the 
 start somehow, but was wondering if might make sense to have a keyword 
 such as "using", but allow it on all block statements, like-so:
 
// Original use-case of repeat … while
repeat using (var i = 0) {
// Do something
} while (i < 20)
 
// for … in demonstrating combination of using and where
for eachItem in theItems using (var i = 0) where (i < 20) {
// Do something either until theItems run out or i reaches 20
}
 
// Standard while loop
while let eachItem = it.next() using (var i = 0) where (i < 20) {
// As above, but with an iterator and a while loop and 
 conditional binding to also stop on nil
}
 
// Closure with its own captured variable
let myClosure:(Int) -> Int = using (var i = 0) { i += 1; return i * $0 }
 
// If statements as well
if somethingIsTrue() using (var i = 0) where (i < 20) {
// Do something
}
 
// Or even a do block; while it does nothing functionally new, I quite 
 like it aesthetically
do using (var i = 0) {
// Do something
}
 
 Unifying principle here is that anything created in the using clause 
 belongs to the loop, conditional branch etc. only, but exists outside the 
 block itself (thus persisting in the case of loops and closures). I quite 
 like the possible interaction with where clauses here as a means to avoid 
 simple inner conditionals as well.
 
 Basically the two clauses can work nicely together to avoid some common 
 inner and outer boilerplate, as well as reducing pollution from throwaway 
 variables.
 
 Only one I'm a bit iffy on is the closure; I'm trying to avoid declaring 
 the captured variable externally, but I'm not convinced that having using 
 on its own is clear enough?
 
 Anyway, just an idea!
 
 ___
 swift-evolution mailing list
 swift-evolution@swift.org
 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
Not much, I think. The `where` clause already exists, conditional `let` and 
`var` binding already exists. It'd take loosening up conditional binding rules 
a bit and expanding the lexical structure to include `let` and `var` bindings 
in `repeat`.

> On Jun 10, 2017, at 2:01 PM, Goffredo Marocchi  wrote:
> 
> Quite interesting :), what impact would it have on the compiler?
> 
> Sent from my iPhone
> 
> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution 
> > wrote:
> 
>> I think a better way of achieving this would be to use the already existing 
>> `where` keyword in loops. The way it works right now is as follows:
>> 
>> let many = [1, 2, 3, 4, 5]
>> for each in many where each % 2 == 0 {
>>  print("found an even number: \(each)")
>> }
>> 
>> Unfortunately, unlike all other conditional scopes, `where` does not allow 
>> `let` and `var` bindings in it, so I'd suggest we add ability to do that:
>> 
>> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
>> for each in many where let number = each {
>>  print("found a non-nil number: \(number)")
>> }
>> 
>> Or, more interestingly:
>> 
>> for each in many where let number = each, number % 2 == 0 {
>>  print("found a non-nil even number: \(number)")
>> }
>> 
>> And in case of a while loop:
>> 
>> var optional: Int? = 1
>> while let nonoptional = optional {
>>  if nonoptional >= 10 {
>>  optional = nil
>>  }
>>  optional = nonoptional + 1
>> }
>> 
>> But this is only for optional unpacking, so another addition would be to 
>> allow any `let` and `var` bindings in conditional scopes without them 
>> contributing to the condition itself:
>> 
>> while let a = 0, a < 10 {
>>  a += 1
>>  print(a)
>> }
>> 
>> And finally, allow these bindings in `repeat`:
>> 
>> repeat let a = 0 {
>>  a += 1
>>  print(0)
>> } while a < 10
>> 
>> I think **if** the core team would consider this a worthwhile addition, this 
>> would be a less invasive and more intuitive way of achieving what you want.
>> 
>>> On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution 
>>> > wrote:
>>> 
>>> Not sure if my e-mail didn't go through or if discussion just fizzled out; 
>>> one other benefit if we ever move to a proper message board is we might 
>>> gain the ability to bump topics. Anyway, I'll resend my message just in 
>>> case:
>>> 
>>> 
>>> 
>>> Just to add my thoughts, as I like the idea of adding the variables to the 
>>> start somehow, but was wondering if might make sense to have a keyword such 
>>> as "using", but allow it on all block statements, like-so:
>>> 
>>> // Original use-case of repeat … while
>>> repeat using (var i = 0) {
>>> // Do something
>>> } while (i < 20)
>>> 
>>> // for … in demonstrating combination of using and where
>>> for eachItem in theItems using (var i = 0) where (i < 20) {
>>> // Do something either until theItems run out or i reaches 20
>>> }
>>> 
>>> // Standard while loop
>>> while let eachItem = it.next() using (var i = 0) where (i < 20) {
>>> // As above, but with an iterator and a while loop and 
>>> conditional binding to also stop on nil
>>> }
>>> 
>>> // Closure with its own captured variable
>>> let myClosure:(Int) -> Int = using (var i = 0) { i += 1; return i * $0 }
>>> 
>>> // If statements as well
>>> if somethingIsTrue() using (var i = 0) where (i < 20) {
>>> // Do something
>>> }
>>> 
>>> // Or even a do block; while it does nothing functionally new, I quite 
>>> like it aesthetically
>>> do using (var i = 0) {
>>> // Do something
>>> }
>>> 
>>> Unifying principle here is that anything created in the using clause 
>>> belongs to the loop, conditional branch etc. only, but exists outside the 
>>> block itself (thus persisting in the case of loops and closures). I quite 
>>> like the possible interaction with where clauses here as a means to avoid 
>>> simple inner conditionals as well.
>>> 
>>> Basically the two clauses can work nicely together to avoid some common 
>>> inner and outer boilerplate, as well as reducing pollution from throwaway 
>>> variables.
>>> 
>>> Only one I'm a bit iffy on is the closure; I'm trying to avoid declaring 
>>> the captured variable externally, but I'm not convinced that having using 
>>> on its own is clear enough?
>>> 
>>> Anyway, just an idea!
>>> 
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>>> 
>> 
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org 
>> 

Re: [swift-evolution] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Goffredo Marocchi via swift-evolution
Quite interesting :), what impact would it have on the compiler?

Sent from my iPhone

> On 10 Jun 2017, at 11:46, Gor Gyolchanyan via swift-evolution 
>  wrote:
> 
> I think a better way of achieving this would be to use the already existing 
> `where` keyword in loops. The way it works right now is as follows:
> 
> let many = [1, 2, 3, 4, 5]
> for each in many where each % 2 == 0 {
>   print("found an even number: \(each)")
> }
> 
> Unfortunately, unlike all other conditional scopes, `where` does not allow 
> `let` and `var` bindings in it, so I'd suggest we add ability to do that:
> 
> let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
> for each in many where let number = each {
>   print("found a non-nil number: \(number)")
> }
> 
> Or, more interestingly:
> 
> for each in many where let number = each, number % 2 == 0 {
>   print("found a non-nil even number: \(number)")
> }
> 
> And in case of a while loop:
> 
> var optional: Int? = 1
> while let nonoptional = optional {
>   if nonoptional >= 10 {
>   optional = nil
>   }
>   optional = nonoptional + 1
> }
> 
> But this is only for optional unpacking, so another addition would be to 
> allow any `let` and `var` bindings in conditional scopes without them 
> contributing to the condition itself:
> 
> while let a = 0, a < 10 {
>   a += 1
>   print(a)
> }
> 
> And finally, allow these bindings in `repeat`:
> 
> repeat let a = 0 {
>   a += 1
>   print(0)
> } while a < 10
> 
> I think **if** the core team would consider this a worthwhile addition, this 
> would be a less invasive and more intuitive way of achieving what you want.
> 
>> On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution 
>>  wrote:
>> 
>> Not sure if my e-mail didn't go through or if discussion just fizzled out; 
>> one other benefit if we ever move to a proper message board is we might gain 
>> the ability to bump topics. Anyway, I'll resend my message just in case:
>> 
>> 
>> 
>> Just to add my thoughts, as I like the idea of adding the variables to the 
>> start somehow, but was wondering if might make sense to have a keyword such 
>> as "using", but allow it on all block statements, like-so:
>> 
>>  // Original use-case of repeat … while
>>  repeat using (var i = 0) {
>>  // Do something
>>  } while (i < 20)
>> 
>>  // for … in demonstrating combination of using and where
>>  for eachItem in theItems using (var i = 0) where (i < 20) {
>>  // Do something either until theItems run out or i reaches 20
>>  }
>> 
>>  // Standard while loop
>>  while let eachItem = it.next() using (var i = 0) where (i < 20) {
>>  // As above, but with an iterator and a while loop and 
>> conditional binding to also stop on nil
>>  }
>> 
>>  // Closure with its own captured variable
>>  let myClosure:(Int) -> Int = using (var i = 0) { i += 1; return i * $0 }
>> 
>>  // If statements as well
>>  if somethingIsTrue() using (var i = 0) where (i < 20) {
>>  // Do something
>>  }
>> 
>>  // Or even a do block; while it does nothing functionally new, I quite 
>> like it aesthetically
>>  do using (var i = 0) {
>>  // Do something
>>  }
>> 
>> Unifying principle here is that anything created in the using clause belongs 
>> to the loop, conditional branch etc. only, but exists outside the block 
>> itself (thus persisting in the case of loops and closures). I quite like the 
>> possible interaction with where clauses here as a means to avoid simple 
>> inner conditionals as well.
>> 
>> Basically the two clauses can work nicely together to avoid some common 
>> inner and outer boilerplate, as well as reducing pollution from throwaway 
>> variables.
>> 
>> Only one I'm a bit iffy on is the closure; I'm trying to avoid declaring the 
>> captured variable externally, but I'm not convinced that having using on its 
>> own is clear enough?
>> 
>> Anyway, just an idea!
>> 
>> ___
>> 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] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
I think a better way of achieving this would be to use the already existing 
`where` keyword in loops. The way it works right now is as follows:

let many = [1, 2, 3, 4, 5]
for each in many where each % 2 == 0 {
print("found an even number: \(each)")
}

Unfortunately, unlike all other conditional scopes, `where` does not allow 
`let` and `var` bindings in it, so I'd suggest we add ability to do that:

let many: [Int?] = [1, 2, nil, 3, 4, nil, 5]
for each in many where let number = each {
print("found a non-nil number: \(number)")
}

Or, more interestingly:

for each in many where let number = each, number % 2 == 0 {
print("found a non-nil even number: \(number)")
}

And in case of a while loop:

var optional: Int? = 1
while let nonoptional = optional {
if nonoptional >= 10 {
optional = nil
}
optional = nonoptional + 1
}

But this is only for optional unpacking, so another addition would be to allow 
any `let` and `var` bindings in conditional scopes without them contributing to 
the condition itself:

while let a = 0, a < 10 {
a += 1
print(a)
}

And finally, allow these bindings in `repeat`:

repeat let a = 0 {
a += 1
print(0)
} while a < 10

I think **if** the core team would consider this a worthwhile addition, this 
would be a less invasive and more intuitive way of achieving what you want.

> On Jun 10, 2017, at 1:31 PM, Haravikk via swift-evolution 
>  wrote:
> 
> Not sure if my e-mail didn't go through or if discussion just fizzled out; 
> one other benefit if we ever move to a proper message board is we might gain 
> the ability to bump topics. Anyway, I'll resend my message just in case:
> 
> 
> 
> Just to add my thoughts, as I like the idea of adding the variables to the 
> start somehow, but was wondering if might make sense to have a keyword such 
> as "using", but allow it on all block statements, like-so:
> 
>   // Original use-case of repeat … while
>   repeat using (var i = 0) {
>   // Do something
>   } while (i < 20)
> 
>   // for … in demonstrating combination of using and where
>   for eachItem in theItems using (var i = 0) where (i < 20) {
>   // Do something either until theItems run out or i reaches 20
>   }
> 
>   // Standard while loop
>   while let eachItem = it.next() using (var i = 0) where (i < 20) {
>   // As above, but with an iterator and a while loop and 
> conditional binding to also stop on nil
>   }
> 
>   // Closure with its own captured variable
>   let myClosure:(Int) -> Int = using (var i = 0) { i += 1; return i * $0 }
> 
>   // If statements as well
>   if somethingIsTrue() using (var i = 0) where (i < 20) {
>   // Do something
>   }
> 
>   // Or even a do block; while it does nothing functionally new, I quite 
> like it aesthetically
>   do using (var i = 0) {
>   // Do something
>   }
> 
> Unifying principle here is that anything created in the using clause belongs 
> to the loop, conditional branch etc. only, but exists outside the block 
> itself (thus persisting in the case of loops and closures). I quite like the 
> possible interaction with where clauses here as a means to avoid simple inner 
> conditionals as well.
> 
> Basically the two clauses can work nicely together to avoid some common inner 
> and outer boilerplate, as well as reducing pollution from throwaway variables.
> 
> Only one I'm a bit iffy on is the closure; I'm trying to avoid declaring the 
> captured variable externally, but I'm not convinced that having using on its 
> own is clear enough?
> 
> Anyway, just an idea!
> 
> ___
> 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] Rekindling: "Extending declaration scope to condition for `repeat { } while ()"

2017-06-10 Thread Haravikk via swift-evolution
Not sure if my e-mail didn't go through or if discussion just fizzled out; one 
other benefit if we ever move to a proper message board is we might gain the 
ability to bump topics. Anyway, I'll resend my message just in case:



Just to add my thoughts, as I like the idea of adding the variables to the 
start somehow, but was wondering if might make sense to have a keyword such as 
"using", but allow it on all block statements, like-so:

// Original use-case of repeat … while
repeat using (var i = 0) {
// Do something
} while (i < 20)

// for … in demonstrating combination of using and where
for eachItem in theItems using (var i = 0) where (i < 20) {
// Do something either until theItems run out or i reaches 20
}

// Standard while loop
while let eachItem = it.next() using (var i = 0) where (i < 20) {
// As above, but with an iterator and a while loop and 
conditional binding to also stop on nil
}

// Closure with its own captured variable
let myClosure:(Int) -> Int = using (var i = 0) { i += 1; return i * $0 }

// If statements as well
if somethingIsTrue() using (var i = 0) where (i < 20) {
// Do something
}

// Or even a do block; while it does nothing functionally new, I quite 
like it aesthetically
do using (var i = 0) {
// Do something
}

Unifying principle here is that anything created in the using clause belongs to 
the loop, conditional branch etc. only, but exists outside the block itself 
(thus persisting in the case of loops and closures). I quite like the possible 
interaction with where clauses here as a means to avoid simple inner 
conditionals as well.

Basically the two clauses can work nicely together to avoid some common inner 
and outer boilerplate, as well as reducing pollution from throwaway variables.

Only one I'm a bit iffy on is the closure; I'm trying to avoid declaring the 
captured variable externally, but I'm not convinced that having using on its 
own is clear enough?

Anyway, just an idea!

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


Re: [swift-evolution] [Proposal] Uniform Initialization Syntax

2017-06-10 Thread Gor Gyolchanyan via swift-evolution
> 
> This is a very interesting read.
> 

Thanks you! I tried to make it as clear and detailed as possible.  

> 
> We did not discuss the 'indirect' idea at all on this list. Did you come up 
> with it just now? In any case, my suggestion as to moving forward would be 
> this:
> 
I was writing the proposal and was just about to write `factory init`, when it 
occurred to me: enums already have a keyword that does something very similar. 
It seemed to me that an initializer that doesn't initialize the instance 
in-place, but returns a completely separate instance from somewhere else, is 
kinda "indirectly" initializing the instance. Plus, the already established 
keyword and its semantic would reduce the learning curve for this new feature 
and separate it from a single specific use case (the "factory method" pattern).

> 
> - Do you feel that both halves of your draft (expanding `return` in 
> initializers, and `indirect` initializers) should absolutely be one proposal, 
> or can they be separated?
> 
I think the `return` can be easily implemented first, while opening up an 
opportunity to later implement `indirect init`. The reason why I unified them 
was that the `return` idea on its own has very limited merit and could the 
thought of as a low-priority cosmetic enhancement. I wouldn't want it to be 
viewed that way because the primary purpose of that idea is to enable `indirect 
init` (which Cocoa and Cocoa Touch developers would be very happy about). 

> 
> a) If they can be separated because each half has individual merit, then 
> these ideas may be more likely to succeed as separate proposals, as each can 
> be critiqued fully and judged independently as digestible units.
> 

Very good point. The challenge is to correctly separate them, without losing 
context in their respective proposals and without bleeding the proposals into 
each other.


> 

> b) If you intend to tackle all your ideas all at once, that's going to be a 
> much bigger change--in terms of review effort, likely bikeshedding, and 
> implementation effort. It'll probably be best to solicit initial feedback on 
> this list first about `indirect` initializers, even if just to familiarize 
> the community with the idea, before launching into a pitch of the whole 
> proposal.
> 

I'd never send a pull request to swift-evolution without thoroughly discussing 
it here. I just though, if I'm going to write a whole proposal with examples 
and motivation, it would be easier to demonstrate it and discuss in with the 
community If I just went ahead and wrote the whole thing and sent the link. 
This way it would be clearer to the reader and the discussed changes would be 
accurately reflected by the commits I'd make to my proposal.

Original Message

> On Jun 10, 2017, at 2:38 AM, Daryle Walker via swift-evolution 
>  wrote:
> 
> On Fri, Jun 9, 2017 at 5:32 PM, Gor Gyolchanyan  > wrote:
> Forked swift-evolution, created a draft proposal:
> 
> https://github.com/technogen-gg/swift-evolution/blob/master/proposals/-uniform-initialization.md
>  
> 
> 
> This is my first proposal, so I might have missed something or composed it 
> wrong, so please feel free to comment, fork and send pull requests. 
> 
> 
> This is a very interesting read. We did not discuss the 'indirect' idea at 
> all on this list. Did you come up with it just now? In any case, my 
> suggestion as to moving forward would be this:
> 
> - Do you feel that both halves of your draft (expanding `return` in 
> initializers, and `indirect` initializers) should absolutely be one proposal, 
> or can they be separated?
> 
> a) If they can be separated because each half has individual merit, then 
> these ideas may be more likely to succeed as separate proposals, as each can 
> be critiqued fully and judged independently as digestible units.
> 
> b) If you intend to tackle all your ideas all at once, that's going to be a 
> much bigger change--in terms of review effort, likely bikeshedding, and 
> implementation effort. It'll probably be best to solicit initial feedback on 
> this list first about `indirect` initializers, even if just to familiarize 
> the community with the idea, before launching into a pitch of the whole 
> proposal.
> 
> 
>> On Jun 9, 2017, at 3:24 PM, Xiaodi Wu > > wrote:
>> 
>> Cool. I have reservations about idea #3, but we can tackle that another day. 
>> (Real life things beckon.) But suffice it to say that I now really, really 
>> like your idea #2.
>> On Fri, Jun 9, 2017 at 08:06 Gor Gyolchanyan > > wrote:
>> You know, come to think of it, I totally agree, and here's why:
>> A normal initializer (if #2 is accepted) would *conceptually* have the 
>> signature:
>> 
>> mutating