Re: [swift-evolution] Extending init checks for property initialization

2016-04-29 Thread Chris Lattner via swift-evolution

> On Apr 28, 2016, at 5:49 PM, David Sweeris via swift-evolution 
>  wrote:
> 
> 
>> On Apr 28, 2016, at 11:50 AM, Vladimir.S via swift-evolution 
>>  wrote:
>> 
>> I think I like this idea. It is clear that it is init() and 'defer' says 
>> that it is called at the end of each init. IMO we need exactly some kind of 
>> 'init' as only in init we can set un-initialized stored properties.
>> 
>> But, why implicitly unwrapped optionals are not solution here? I.e.
> 
> To avoid the extra overhead. Also, they’re sorta going away in Swift 3: 
> https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md

SE-0054 shouldn’t eliminate use of IUO’s for properties that are “delay 
initialized”.  The only effect it will have is that it will prevent downstream 
references to those properties from accidentally propagating the IUO’ness.

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


Re: [swift-evolution] [Pitch] Requiring proactive overrides for default protocol implementations.

2016-04-29 Thread Matthew Judge via swift-evolution
I believe the following idea was brought up on the list the last time this 
topic came up, but I think it has a number of advantages and gets rid of the 
need for a 'required' keyword completely. I have reservations on the 'override' 
keyword as well, but the following idea would not preclude adding the 
'override' keyword.

If an extension adds protocol conformance, only methods implementing the 
protocol are allowed in the body.  All methods from the protocol do not need to 
be implemented in the extension, so long as the type conforms overall.

struct Foo {
   func a() {}
}

protocol A {
   func a()
}
protocol B {
   func b()
}
protocol C {} 


extension Foo: A { } // retroactive modeling, no error

extension Foo: B {
   func b() {} // compiles, but "near miss" would not
}

extension Foo: C {
   func d() {} // error, d() not part of protocol C
}

Advantages:
- Clarifies intent... If you are implementing a method in an extension that 
declares a protocol conformance, it has to satisfy that one of that protocol's 
requirements
- Eliminates "near-miss" mistakes when implementing a function in an extension 
that declares protocol conformance, even in protocol has a default 
implementation (it would be an error to implement the non-matching-but-almost 
func)
- Fully supports retroactive modeling
- No new keywords required

Disadvantages:
- Source breaking change for any code that currently declares protocol 
conformance in an extension and implements an unrelated method
- Potential inconsistency with base type declaration (does this rule apply only 
to extensions or the initial declaration of the type?)
- Does not stop you from accidentally writing a implementation for a method 
that already has a default implementation in the protocol (though nothing here 
precludes the addition of adding 'override' as well)

Effectively, the only change required to current code would be to modify the 
above implementation of:

extension Foo: C {
   func d() {}
}

To read:

extension Foo: C {}
extension Foo {
   func d() {}
}

On Apr 29, 2016, at 11:44, Stephen Canon via swift-evolution 
 wrote:

>> On Apr 29, 2016, at 10:38 AM, Xiaodi Wu via swift-evolution 
>>  wrote:
>> 
>> I'd be keenly interested in something that would improve the experience of 
>> conforming a type to a protocol. I think others would as well. A 
>> sufficiently sophisticated solution would:
>> 
>> * catch unintentional typos that cause required functions to be incorrectly 
>> named
>> * show, ideally prospectively, which required functions have default 
>> implementations
>> * clarify (and this is obviously a cherry-on-top scenario) what protocol 
>> requirements any particular function helps to satisfy as well as which 
>> combination of implementations is used to synthesize a default 
>> implementation of another function (e.g. <= synthesized from < and ==; this 
>> would help to determine whether it might be more efficient to roll your own 
>> override)
>> * support all retroactive modeling scenarios currently supported
>> 
>> I tried to propose a keyword-based solution (less sophisticated than yours) 
>> a while back, and I've been convinced that the drawbacks in terms of 
>> decreased expressiveness in retroactive modeling might be insurmountable. 
>> Perhaps it would be worthwhile exploring improvements in tooling and 
>> documentation (including annotation of the code itself) in order to address 
>> some of these areas?
> 
> Yeah, I think this is something that tooling / editors could really help 
> with.  I would love it if when I typed:
> 
>   struct Foo: Bar
> 
> or
> 
>   extension Foo: Bar
> 
> a skeleton with the missing Bar APIs was auto-generated for me to fill in.  
> This would make it much easier to get conformances right, and require less 
> typing instead of more.
> 
> – Steve
> ___
> 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] multi-line string literals.

2016-04-29 Thread Brent Royal-Gordon via swift-evolution
> This would ultimately be my favorite approach. I do like the underscores, 
> because they're unobtrusive and don't distract the eye, but I'm interested to 
> see alternative suggestions. However, I understand this is not considered in 
> scope for the current proposal. Is the intention to propose alternate 
> delimiters for Swift 3 now or wait?

My goal is to get Swift 3 string literals to the minimum viable feature set for 
tasks like scripting, templating, using regex libraries, and generating code. 
In my mind, the features I discuss in the "Future directions for string 
literals" section break down like this:

ABSOLUTELY NECESSARY—I definitely intend to propose these for Swift 3.

* Readable multiline strings
* Ability to disable escapes

REALLY NICE TO HAVE—We'll see how much the community wants them, and how much 
the core team thinks it can handle.

* Alternate delimiters
* Ability to disable escapes except for interpolation (and perhaps to 
selectively disable other escapes)

REALLY NICE TO HAVE, BUT WE CAN'T—I would love to do these, but they're too 
hard for Swift 3.

* Very long, minimally massaged strings (i.e. heredocs)

CONVENIENCES—If we had infinite time...but we don't. And they might be dumb 
anyway.

* Whitespace normalization
* Embedded comments
* Localization
* Default modifier control

NOT INVENTED YET—Requires huge supporting designs we just don't have.

* Regex literals
* User-specified modifiers

I think we should definitely propose the items in "Absolutely Necessary" and 
consider proposing the ones in "Really Nice To Have" for Swift 3. I think we 
should definitely do the "Really Nice To Have, But We Can't" item in Swift 4. I 
think we should revisit and consider the others in Swift 4 and beyond.

* * *

I have intentionally described these features very broadly. For instance, I 
said "alternate delimiters", not "the `_` modifier". The specific designs I 
sketched in the proposal are merely examples of solutions to that class of 
problem. Here are a whole slew of other designs just for alternate delimiters:

* Use a different identifier-but-not-capitalizable character, like `$`.
* Use a different single-character ASCII delimiter, like `'`.
* Use a different multi-character delimiter, like `"""`.
* Use a different Unicode delimiter, like smart quotes (`“foo ”`) or French 
quotes (`«foo»`) or Japanese quotes (`⸢foo⸥`).
* Permit arbitrary delimiters bounded by some specific, known character, like 
(just making this up) `'~'`.

That's just off the top of my head—there are probably a hundred more of these. 
What is presented in the "Future directions for string literals" section is a 
series of *example* solutions to illustrate the problems that need solving, not 
necessarily the exact thing we must write a proposal for in a few months or 
years. It's a sketch, not a roadmap.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [swift-dev] [Compiler] Help IR gen in targetting MSVC

2016-04-29 Thread Sangjin Han via swift-evolution
I made a PR https://github.com/apple/swift/pull/2351 introducing os(Cygwin).


2016-04-27 5:54 GMT+09:00 John McCall :

> > On Apr 26, 2016, at 1:39 PM, Joe Groff  wrote:
> >> On Apr 26, 2016, at 1:24 PM, John McCall via swift-evolution <
> swift-evolution@swift.org> wrote:
> >>
> >>> On Apr 26, 2016, at 1:03 PM, Sangjin Han 
> wrote:
> >>> The problem can be solved by modifying that code. Thanks you. I
> thought that code will affect only to the CLong type not Int.
> >>
> >> It changes what 'long' gets imported as.  If there's a Windows API
> defined using 'long' (rather than some more meaningful typedef like
> 'size_t'), it's important for it to be imported as Int32 rather than Int,
> since 'long' is always 32 bits under MSVC.
> >>
> >>> But I meet another problem to fix it. I couldn't find the conditional
> method to distinct x86_64-*-windows-msvc with x86_64-*-windows-cygnus in
> Swift source.
> >>>
> >>> "#if os(Windows)" can not distinct MSVC from Cygwin.
> >>>
> >>> Should I add new condition 'env()' for the environment?
> >>
> >> That is an excellent question.
> >>
> >> My understanding / memory is that, as far as their programming
> interfaces goes, Cygwin and MSVC are very, very different environments.
> Maybe it's useful to have a condition that's true for both environments —
> although I'm not sure why it would — but I don't think it deserves to be as
> prominent as os(Windows).  So my gut reaction is that, rather than adding a
> #env, we ought to just reserve os(Windows) for MSVC compatibility and make
> a new os(Cygwin) for Cygwin.
> >>
> >> This needs to be raised on swift-evolution, though.  CC'ing that list.
> >
> > It's an interesting question. Mingw, Cygwin, and MSVC definitely vary
> greatly in ABI and C language level behavior, but the underlying Win32
> system libraries remain the same. I think it makes sense to consider them
> different os(...) environments, but it would also make sense IMO to have a
> broader platform check for Win32.
>
> If, after import and however much magic, they both end up exposing a
> similarly-typed set of system APIs, I agree that it makes sense to have a
> condition that says "yes, the target has those APIs".  It certainly seems
> like a worthwhile goal for Swift to present them with the same imported
> types.
>
> John.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0032: Add find method to SequenceType

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, Kevin Ballard  wrote:

> On Fri, Apr 29, 2016, at 05:12 PM, Max Moiseev via swift-evolution wrote:
>> HI all,
>>
>>
>> After having discussed this proposal with the members of the standard
>> library team, we would like to propose the following updates:
>>
>> - Since both the language and the standard library have evolved since
>>   it was written, the proposal should reflect these changes (things
>>   like renaming `Generator` to `Iterator`, adjusting for first
>>   argument label rules etc.)
>>> (Actually, while writing this, I discovered
>>> https://github.com/apple/swift-evolution/pull/276)
>> - We believe that renaming `find(_:)` to `first(where:)` would make
>>   call sites more clear
>>
>>> // original proposal
>>> numbers.find { isPrime($0) }
>>> numbers.find(isPrime)
>>>
>>> // suggested update
>>> numbers.first { isPrime($0) }
>>> numbers.first(where: isPrime)
>>>
>>> In the examples above, when the predicate is passed as a trailing
>>> closure, there is no big difference in the invocation, but it changes
>>> when we have a named function that we would like to use as a
>>> predicate.
>>> The Collection protocol already has a property called `first`, that
>>> returns an optional element, it also has a method `index(where:)`. In
>>> this sense `first(where:)` does not introduce new words to the
>>> library vocabulary.
>
> first(where:) is a neat idea, but I'm a little concerned about ambiguity
> with the property in the presence of type errors. Experimentally, if I
> try to call first(where:) with a block with the wrong signature, Swift 3
> produces an unhelpful error about how I cannot call value of a non-
> function type (i.e. the property) instead of recognizing that I'm trying
> to call the function.
>
> Example:
>
> struct Foo {
> var first: Int = 42
>
> func first(where: @noescape Int -> Bool) -> Int {
> return 42
> }
> }
>
> If I try and call `print(Foo().find(where: { true }))`, you'll note that
> the closure has the wrong type signature (it types as `() -> Bool`), and
> the compiler gives me the error:
>
> :1:12: error: cannot call value of non-function type 'Int'
> Foo().first(where: { true })
> ~~~^
>
> Calling it with a block of the correct type works, but having useful
> errors is very important.

That's a QOI bug in the compiler that can be fixed.  IMO we should avoid
designing APIs around temporary limitations of the compiler
implementation.

-- 
Dave

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


Re: [swift-evolution] [Review] SE-0032: Add find method to SequenceType

2016-04-29 Thread Kevin Ballard via swift-evolution
On Fri, Apr 29, 2016, at 05:12 PM, Max Moiseev via swift-evolution wrote:
> HI all,
>
>
> After having discussed this proposal with the members of the standard
> library team, we would like to propose the following updates:
>
> - Since both the language and the standard library have evolved since
>   it was written, the proposal should reflect these changes (things
>   like renaming `Generator` to `Iterator`, adjusting for first
>   argument label rules etc.)
>> (Actually, while writing this, I discovered
>> https://github.com/apple/swift-evolution/pull/276)
> - We believe that renaming `find(_:)` to `first(where:)` would make
>   call sites more clear
>
>> // original proposal
>> numbers.find { isPrime($0) }
>> numbers.find(isPrime)
>>
>> // suggested update
>> numbers.first { isPrime($0) }
>> numbers.first(where: isPrime)
>>
>> In the examples above, when the predicate is passed as a trailing
>> closure, there is no big difference in the invocation, but it changes
>> when we have a named function that we would like to use as a
>> predicate.
>> The Collection protocol already has a property called `first`, that
>> returns an optional element, it also has a method `index(where:)`. In
>> this sense `first(where:)` does not introduce new words to the
>> library vocabulary.
 
first(where:) is a neat idea, but I'm a little concerned about ambiguity
with the property in the presence of type errors. Experimentally, if I
try to call first(where:) with a block with the wrong signature, Swift 3
produces an unhelpful error about how I cannot call value of a non-
function type (i.e. the property) instead of recognizing that I'm trying
to call the function.
 
Example:
 
struct Foo {
var first: Int = 42
 
func first(where: @noescape Int -> Bool) -> Int {
return 42
}
}
 
If I try and call `print(Foo().find(where: { true }))`, you'll note that
the closure has the wrong type signature (it types as `() -> Bool`), and
the compiler gives me the error:
 
:1:12: error: cannot call value of non-function type 'Int'
Foo().first(where: { true })
~~~^
 
Calling it with a block of the correct type works, but having useful
errors is very important.
 
-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0032: Add find method to SequenceType

2016-04-29 Thread Kevin Ballard via swift-evolution
On Thu, Apr 28, 2016, at 10:31 PM, Rod Brown via swift-evolution wrote:
> * What is your evaluation of the proposal?
> +1 for the functionality on CollectionType
> -1 for the functionality on SequenceType
>  
> * Is the problem being addressed significant enough to warrant a change to 
> Swift?
> It’s certainly a helpful addition and one I’ve got an analogous version of in 
> my own projects. Considering this is a simply addition on CollectionType, I 
> think there no reasons not to.
> 
> I’m concerned about this being added to SequenceType. The risks associated 
> with iterating through a sequence where it may be destructive seem to great 
> to me, especially when this can be limited to CollectionType instead.

I don't understand this argument. The whole point of a sequence is to iterate 
over it. Yes, if you have a destructive sequence and you iterate over it 
multiple times it's not going to work right, but I don't see find() as having 
any higher risk of doing this than any of the other methods that iterate over 
the sequence.

Not only that, but I actually find the find() method to be most useful when 
used with Sequence. With Collection you can already just get the index and then 
use that to index into the collection; it's a little verbose, but not awful. 
But the only alternative with Sequence is to write an imperative loop that uses 
a mutable variable.

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


Re: [swift-evolution] [Review] SE-0072: Fully eliminate implicit bridging conversions from Swift

2016-04-29 Thread Jordan Rose via swift-evolution
[Proposal: 
https://github.com/apple/swift-evolution/blob/master/proposals/0072-eliminate-implicit-bridging-conversions.md]

I’m a little concerned about the affect this has on “plist literals”. 
Specifically, I can no longer construct a dictionary like this:

let userInfo: [String: AnyObject] = [
kSomeStandardKey: self.name, // a String
kAnotherKey: self.childNames // an Array of Strings
]
NSNotificationCenter.default().postNotificationName(MyNotification, self, 
userInfo)

The fix isn’t that hard—just add “as NSString” or “as NSArray”—but it is a bit 
of extra noise that we currently don’t have. If the type checker can still 
offer that fix-it, then I’m not sure we’d actually get any compiler 
simplification out of it…although I suppose it might make the happy path faster.

The CFString issue Jacob brought up is also a little unfortunate, although 
that’s about the direction that already requires an explicit coercion. But this 
probably affects calling CF functions that take CFStrings, since IIRC we don’t 
treat that the same as NSString at the moment, and CFArray will never have 
generics.

Of course, I’ve been out of the Cocoa community for a while now, so I don’t 
really have a sense of how often this comes up in practice, and how much the 
explicit coercion costs (psychologically). So I’m with Brent: do we have 
information on the changes needed for real-world projects?

Jordan


> On Apr 26, 2016, at 13:54, Chris Lattner via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of "SE-0072: Fully eliminate implicit bridging conversions from 
> Swift" begins now and runs through May 2. The proposal is available here:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0072-eliminate-implicit-bridging-conversions.md
> 
> Reviews are an important part of the Swift evolution process. All reviews 
> should be sent to the swift-evolution mailing list at:
> 
>   https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> or, if you would like to keep your feedback private, directly to the review 
> manager.
> 
> 
> What goes into a review?
> 
> The goal of the review process is to improve the proposal under review 
> through constructive criticism and, eventually, determine the direction of 
> Swift. When writing your review, here are some questions you might want to 
> answer in your review:
> 
>   * What is your evaluation of the proposal?
>   * Is the problem being addressed significant enough to warrant a change 
> to Swift?
>   * Does this proposal fit well with the feel and direction of Swift?
>   * If you have you used other languages or libraries with a similar 
> feature, how do you feel that this proposal compares to those?
>   * How much effort did you put into your review? A glance, a quick 
> reading, or an in-depth study?
> 
> More information about the Swift evolution process is available at
> 
>   https://github.com/apple/swift-evolution/blob/master/process.md
> 
> Thank you,
> 
> -Chris Lattner
> Review Manager
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [Review] SE-0032: Add find method to SequenceType

2016-04-29 Thread Max Moiseev via swift-evolution
HI all,

After having discussed this proposal with the members of the standard library 
team, we would like to propose the following updates:

- Since both the language and the standard library have evolved since it was 
written, the proposal should reflect these changes (things like renaming 
`Generator` to `Iterator`, adjusting for first argument label rules etc.)
(Actually, while writing this, I discovered 
https://github.com/apple/swift-evolution/pull/276)
- We believe that renaming `find(_:)` to `first(where:)` would make call sites 
more clear

// original proposal
numbers.find { isPrime($0) }
numbers.find(isPrime)

// suggested update
numbers.first { isPrime($0) }
numbers.first(where: isPrime)

In the examples above, when the predicate is passed as a trailing closure, 
there is no big difference in the invocation, but it changes when we have a 
named function that we would like to use as a predicate.
The Collection protocol already has a property called `first`, that returns an 
optional element, it also has a method `index(where:)`. In this sense 
`first(where:)` does not introduce new words to the library vocabulary.

max

> On Apr 28, 2016, at 11:11 AM, Chris Lattner via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of "SE-0032: Add find method to SequenceType" begins now and runs 
> through May 3. The proposal is available here:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0032-sequencetype-find.md
> 
> Reviews are an important part of the Swift evolution process. All reviews 
> should be sent to the swift-evolution mailing list at
> 
>   https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> or, if you would like to keep your feedback private, directly to the review 
> manager.
> 
> What goes into a review?
> 
> The goal of the review process is to improve the proposal under review 
> through constructive criticism and, eventually, determine the direction of 
> Swift. When writing your review, here are some questions you might want to 
> answer in your review:
> 
>   * What is your evaluation of the proposal?
>   * Is the problem being addressed significant enough to warrant a change 
> to Swift?
>   * Does this proposal fit well with the feel and direction of Swift?
>   * If you have you used other languages or libraries with a similar 
> feature, how do you feel that this proposal compares to those?
>   * How much effort did you put into your review? A glance, a quick 
> reading, or an in-depth study?
> 
> More information about the Swift evolution process is available at
> 
>   https://github.com/apple/swift-evolution/blob/master/process.md
> 
> Thank you,
> 
> -Chris Lattner
> Review Manager
> 
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] multi-line string literals.

2016-04-29 Thread Ted F.A. van Gaalen via swift-evolution
>>  let xml = _"
>>  "
>>  " 
>>  " \(author)
>>  " 
>>  "”_

If I am reading and understanding this correctly:
This solution is still delimiter-sensitive and
breaks if“_ delimiter is found somewhere within the data,
because it is interpreted as end-of-string.

I wrote already about my solution   
which solves the above deficiency, 
because it does not use delimiters at all.

I have thought it all over and cleaned it up. Here it is again,
hopefully this description is more clear and readable.

Data Line Operators. 

For convenience, I call these \\ and \@ :  “data-line-operators” .
(of course, they are pseudo operators) 
Other two? character combinations for these operators are also possible. 


The  \@  data-line-operator:   
 -  takes character data "as-is” without any conversion.
 -  respects (includes) source-file line terminators.
 -  all spaces in-between and up to the source line's end are included.
 -  comments // are not seen as comments but read as data. 
 -  the \@ on its own (without anything else to the right) is implicitly an 
empty line.  
   

The  \\   data-line-operator:
   -  converts escaped chars like \t \n  and \(var) substitution, as with 
“normal" string literals.
   -  ignores trailing spaces and source-file line terminators.
   -  respects  // comments on the same line and will not include these as 
data. 
   -  the  \\ on its own is interpreted as \n (line feed)  thus (optionally) 
eliminating the 
  need for  \n usage. 

Both operators allow 0…n spaces/tabs on its left side, 
thus indentation is supported.

Example 1. The \@ operator: 

 // 1.  multi-line string literal with data lines as is. 
 // It loads each line (part) up to and including the source-file-line- 
end:
 // you can use all available characters without problems, 
 // even \\ and \@  thus allowing you to nest e.g. Swift statements...  

 let xml =
 \@
 \@  
 \@  // this is not 
regarded as a comment.
 \@   //¯\"_(ツ)_//
 \@
 \@   
 

   Example 2, The \\ operator: 
   // Multi-line string literal with data lines with \n \t etc. respected: 

 var str =
 \\This is line one.\nThis is line two, with a few \t\t\t 
tabs in it...
 \\
 \\This is line three: there are \(cars) // 
this is a comment.
 \\ waiting in the garage. This is still line three

 The first \@ or \\ must be on a new line, this is an error:

 let str =  /@data data data data…...
 /@data.


A block of \@  or \\ lines must be contiguous: with no other lines in-between.
An empty line or other source line implicitly ends the 
\\ or \@ block of lines. There is no terminator. 

 \@ and \\  lines can be mixed together in the same block.
 Should this be allowed? 



Imho even easier to understand and simple.

I could make a proposal for this later in May.

@Vladimir: sorry I didn’t respond directly on your email
You’re right. Our ideas about this have some similarity? 
Your point: 
   "and I believe I can prove we need some start-of-line marker)” :
 I think so too, that’s why I suggest the \\ and \@ data-line-operators. 
as described here.  

Too busy, packing things to move to www.speyer.de
I will read swift-evolution, but will probably not
respond until after the 12th of May or so.

Although away, some feedback would be nice, thank you.

Kind Regards
TedvG





Fri, 29 Apr 2016 08:20:34 -0600 Erica Sadun wrote: 

>> On Apr 28, 2016, at 4:52 PM, Brent Royal-Gordon via swift-evolution 
>> > wrote:
>> 
>>> Did you ever really use multiline string literals before?
>> 
>> Yes. I used Perl in the CGI script era. Believe me, I have used every 
>> quoting syntax it supports extensively, including `'` strings, `"` strings, 
>> `q` strings, `qq` strings, and heredocs. This proposal is educated by 
>> knowledge of their foibles.
>> 
>> As outlined in the "Future directions for string literals in general" 
>> section, I believe alternate delimiters (so you can embed quotes) are a 
>> separate feature and should be handled in a separate proposal. Once both 
>> features are available, they can be combined. For instance, using the 
>> `_"foo"_` syntax I sketch there for alternate delimiters, you could say:
>> 
>>  let xml = _"
>>  "
>>  " 
>>  " \(author)
>>  " 
>>  ""_
> 
> Other than the underscores (I'm not sold on them but I could live with them), 
> this is my favorite approach:
> 
> * It supports indented 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0017: Change Unmanaged to use UnsafePointer

2016-04-29 Thread Jordan Rose via swift-evolution

> On Apr 28, 2016, at 17:22, Andrew Trick via swift-evolution 
>  wrote:
> 
> 
>> On Apr 28, 2016, at 11:10 AM, Chris Lattner  wrote:
>> 
>> Hello Swift community,
>> 
>> The review of "SE-0017: Change Unmanaged to use UnsafePointer" begins now 
>> and runs through May 3. The proposal is available here:
>> 
>>  
>> https://github.com/apple/swift-evolution/blob/master/proposals/0017-convert-unmanaged-to-use-unsafepointer.md
> 
> 
> I have some concerns, but let me just suggest a simple alternative and see 
> what people think...
> 
> - Leave the existing from/toOpaque API until we can come up with a better 
> plan for moving away from OpaquePointer.
> 
> - Add initializers to avoid boilerplate, but only for "safe" variants of the 
> cast:
> 
> extension Unmanaged {
>  @_transparent
>  public init(_ from : UnsafePointer)
> 
>  @_transparent
>  public init?(_ from : UnsafePointer?)
> }
> 
> extension UnsafeMutablePointer where Pointee : AnyObject {
>  @_transparent
>  public init(_ from : Unmanaged)
> 
>  @_transparent
>  public init?(_ from : Unmanaged?)
> }

This isn’t correct; an UnsafeMutablePointer is a pointer to a reference to 
Foo. Unmanaged is a wrapper around ‘unowned Foo’, i.e. it’s just the 
reference.


> 
> - This doesn't solve the stated problem of passing unmanaged pointers to 
> 'void*' imports. Is that really an issue? I believe the correct fix is to 
> stop importing 'void*' as UnsafePointer. We should have a nominally 
> distinct "opaque" pointer type, 'void*' should be imported as that type, and 
> casting from any UnsafePointer to the opaque pointer type should be inferred 
> and implicit for function arguments. I can send a proposal for eliminating 
> UnsafePointer next week, but the scope of that proposal will be much 
> broader.

This is one of the few major use cases for Unmanaged: passing objects through C 
context pointers. If the type of a ‘void *’ pointer changes, then this proposal 
should use that type.

(The other supported uses of Unmanaged are interacting with existing CF APIs 
that haven’t been audited, and dealing with fields of structs with class type, 
neither of which use fromOpaque/toOpaque. That last actually isn’t implemented 
correctly at the moment; we’re assuming those are all strong references, which 
they aren’t.)

Jordan

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


Re: [swift-evolution] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, Kevin Ballard  wrote:

> On Thu, Apr 28, 2016, at 11:11 AM, Chris Lattner via swift-evolution wrote:
>> Hello Swift community,
>> 
>> The review of "SE-0045: Add scan, prefix(while:), drop(while:), and iterate 
>> to the stdlib" begins now and runs through May 3. The proposal is available 
>> here:
>> 
>>  
>> https://github.com/apple/swift-evolution/blob/master/proposals/0045-scan-takewhile-dropwhile.md
>
> The proposal has been updated as per feedback from the core team
> (https://github.com/apple/swift-evolution/pull/275). This includes
> removing some last vestiges of Swift 2 naming as well as replacing
> `iterate(_:apply:)` with an overloaded function `unfold(_:applying:)`.

Thanks, Kevin!

-- 
Dave

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, Kevin Ballard  wrote:

> On Thu, Apr 28, 2016, at 02:13 PM, Pyry Jahkola via swift-evolution wrote:
>
> I would really like a different name for scan. While it’s the term of art
> for Haskell and co, it really seems meaningless to regular programmers
> (why is “scanning” the way you produce an array of intermediate
> reduces?), and it would be better to follow the pattern already
> established elsewhere in the library to give friendlier names e.g.
> flatMap instead of bind, reduce instead of fold.
>
> I think Python calls it accumulate:
> http://docs.python.org/3/library/itertools.html#itertools.accumulate
>
> FWIW, Clojure calls it `reductions` which aligns pretty nicely with the
> `reduce` counterpart.
>
> I like it.

+1!

-- 
Dave

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, Kevin Ballard  wrote:

> On Thu, Apr 28, 2016, at 11:48 AM, Joe Groff via swift-evolution wrote:
>> One thing I've been thinking about with regards to the existing
>> `reduce` operation is whether it would be better expressed in Swift
>> as taking its closure as (inout State, Element) -> Void rather than
>> (State, Element) -> State. Doing so would avoid many of the
>> accidentally-quadratic issues with the current formulation of
>
>> reduce:
>> 
>>  arrayOfArrays.reduce([], combine: +) // quadratic temporary arrays
>>  arrayOfArrays.inPlaceReduce([], combine: +=) // can be linear by 
>> appending arrays in-place
>> 
>> Thanks to the scoped semantics of `inout`, there's no hazard of the
>> mutable state reference being escaped, so the inout form is
>> isomorphic to the traditional pure form of reduce.
>> 
>> Now `scan`-ing to generate an array of intermediate arrays is
>> inherently quadratic, since each intermediate array shows up as a
>> distinct copy in the resulting collection. However, if someone used
>> `scan` to produce a sequence of tree data structures instead of flat
>> arrays, it could still be interesting to share structure among the
>> intermediate states collected by `scan` by performing an in-place
>> operation to generate new values instead of an out-of-place
>> operation. It might be interesting to consider a similar signature
>> change to `scan` for these same reasons.
>
> That's an interesting idea. Taking the state as an inout parameter
> seems useful, but it does mean breaking with precedent from other
> languages and I do worry slightly about the ergonomics (not all
> operations have mutating counterparts, 

That's easy; you just mutate the whole state using assignment in the
closure:

  state = nonmutating(state)

> though you could also say that there's mutating methods that don't
> have trivial non-mutating versions too).

That one is harder unless you know you have value semantics; you need a
way to copy the state to create a non-mutating operation from a mutating one.

> That said, regarding using `scan` to produce a sequence of tree data
> structures, I'd expect non-mutating operations to be able to share
> state just as effectively as COW mutating operations.

Good point.

-- 
Dave

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


Re: [swift-evolution] Auto Unwrapping Of Optionals

2016-04-29 Thread Rod Brown via swift-evolution
I agree that it's a pain to have to unwrap after this, but this proposal 
worries me somewhat.

I don't think we can safely guarantee that the value is non-null outside a very 
limited subset of cases, and we're breaking the simple, general and reasonable 
syntax of Swift for a very minor convenience win. 

Additionally, this will play out like magic. Suddenly an optional starts 
dynamically changing its behaviour. I can't see where the compiler begins or 
ends the assertion of the value's non-null state, and so you have code that, 
with a little shifting around, begins to fail to even compile, based on 
something the user cannot see.

I think we have better mechanisms to handle this type of thing, like the 
if/guard let syntax, and implicitly unwrapped optionals.

> On 30 Apr 2016, at 12:37 AM, Tod Cunningham via swift-evolution 
>  wrote:
> 
> I'm new to the swift evolution community, but I wanted to toss an idea out 
> there to get some feedback on it. So here it goes...
> 
> Currently, if you assign a non-nil value to an optional and then want to 
> access that optional later, in the same context, you need to manually unwrap 
> the value.  This is usually done either by using "!" or by using something 
> like "if let" or guard.
> 
> What would it be like if the compiler could auto unwrap, in cases where in 
> knows the optional will have some value?  This would make the code "clean" 
> and still be safe.
> 
> This concept of Auto Unwrapping of Optionals is similar to Implicitly 
> Unwrapped Optionals, but is only applied when the compiler knows it is safe 
> to do so.
> 
> Take the following example:
> 
> class Test {
>var today: NSDate? = nil
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as an optional
>let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow  // 
> Requires ! or (if let) to unwrap
>// ... do stuff with timeInterval ...
>}
> }
> 
> With the above example, the compiler could known that today has a value after 
> it's set in the test method.  So why couldn't the compiler auto unwrap it 
> when accessed?  This would mean manual unwrapping would be unnecessary:
> 
> class Test {
>var today: NSDate? = nil
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as a value (not an 
> optional)
>let timeInterval: NSTimeInterval = today.timeIntervalSinceNow  // No ! 
> required (auto unwrapped)
>// ... do stuff with timeInterval ...
>}
> }
> 
> If the value later gets set to an optional value, then it will no longer be 
> auto unwrapable :
> 
> class Test {
>var today: NSDate? = nil
> 
>func optionalDay() -> NSDate? {
>return NSDate()
>}
> 
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as a value (not an 
> optional)
>let timeInterval: NSTimeInterval = today.timeIntervalSinceNow// No 
> ! required (auto unwrapped)
>let timeInterval2: NSTimeInterval = today!.timeIntervalSinceNow  // 
> Explicit unwrapping would still be allowed
> 
>// If today is assigned an optional value, we can no longer auto 
> unwrap it
>today = optionalDay()
>print("Today is \(today)")   // Would be printed as an optional
>let timeInterval3: NSTimeInterval = today!.timeIntervalSinceNow  // 
> manual unwrapping would be required
>}
> }
> 
> Note in the above example, explicit unwrapping would still be allow.  The 
> variable is still an optional.  This allows for existing code to remain 
> unchanged.
> 
> This change would encourage less use of forced unwrapping "!", generally 
> require the developer to write less code, and would maintain code safety.  On 
> the down side, it is performing some compiler “magic”.  It would be yet 
> another thing to explain when trying to introduce people to swift and 
> especially optionals.
> 
> What do you all think, would something like this be worth pursuing, what 
> other pluses or minus would this introduce, has something like this already 
> been discussed?
> 
> Thanks,
> Tod Cunningham
> 
> ___
> 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] Eliminate inconsistencies among primary collection types

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, "Wolfgang H. via swift-evolution" 
 wrote:

> A. When trying to declare nested collection types an inconsistency
>is unveiled:

AFAICT this is all due to the lack of a compiler feature called
“constrained conformances,” which we'd like to implement but don't have
yet.

-- 
Dave

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


Re: [swift-evolution] [Idea] Pin down IteratorProtocol's mutation semantics

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, Brent Royal-Gordon  wrote:

> IteratorProtocol imposes some strange limitations and preconditions
> which basically boil down to "this protocol is fundamentally mutating,
> but we don't want to promise whether you're going to get value or
> reference semantics, so don't do anything that might behave
> differently depending on that, and by the way we can't possibly
> enforce that in the type system, so good luck finding any mistakes
> yourself". 

Actually we could possibly enforce reference semantics.  I have asked
some optimizer folks around here to look into whether it would be
feasible to put a “: class” constraint on IteratorProtocol without
hurting performance, but I'm not sure when they'll be able to get to it.
If someone in the community would like to do some experiments, that
would be great.

> As far as I can tell, this is because some iterators *must* provide
> reference semantics (e.g. when reading from a socket), while others
> can be implemented perhaps more efficiently with a value type.

It's all speculation until we see what the optimizer can do (and can be
trained to do).  I believe we already are promoting some class instances
to the stack, but I could be wrong.

> How bad would it be to force all iterators to provide reference
> semantics by making IteratorProtocol a class protocol? Particularly if
> we assume that iterators could generally be made `final`?
>
> Alternatively, how valuable is it to specify that you can't use an
> iterator in a way that would expose whether it is a reference or a
> value type? 

Well, that's not a problem specific to iterators at all.  The general
problem is that:

* Reference semantics and value semantics are fundamentally different.

* We have no way to declare in the language that something has value or
  reference semantics.  It's possible to write classes whose instances
  have value semantics (make it final and don't provide any mutating
  methods or writable properties) and structs that have reference
  semantics (just make it delegate mutations and comparison to a
  contained class instance), and we haven't outlawed doing so.

I suppose we could *almost* constrain something to having reference
semantics by making it a class protocol with a mutating member, except
for this error: 

  'mutating' isn't valid on methods in classes or class-bound protocols.  

…well, there is this horrible workaround:

  protocol HasMutatingMethod { mutating func f() }
  protocol HasReferenceSemantics : class, HasMutatingMethod {}

Although the semantic requirements on f ought to be enough:

  protocol HasReferenceSemantics : class {
/// Updates `self` to its next state or whatever. <
func f()
  }

I'm sure the standard library is full of generic code that doesn't
actually work with reference types; I know of several specific
instances.

I used to think that we should have a language feature that allows us to
declare value semantics, but I am coming around to the idea that we
ought to simply require structs and enums to have value semantics (and
mutable classes, reference semantics—parenthesized because it just
happens naturally).  I believe we could give some really great
diagnostics for mistakes in this area, both in the compiler and in a
separate static analyzer, and that we could generate correct default
implementations of == and < for almost everything.

> The only iterators I can think of which would *need* to be reference
> types are ones which draw elements from an outside source; for those,
> it's unsurprising that copying doesn't "work". Are there cases I'm not
> thinking of?
>
> Or have I totally misread the situation in some way?

Not at all, except perhaps for thinking that the general problem is
about iterators.  Still, it might be possbile as noted above to solve it
for iterators.

-- 
Dave

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


Re: [swift-evolution] Auto Unwrapping Of Optionals

2016-04-29 Thread Michael Peternell via swift-evolution
I thought about this too, and I think it would be convenient. It feels a bit 
like artificial intelligence though, and I'm not sure how easy it would be to 
implement this. It should be sharply defined what the compiler should infer and 
what not. This can be very hard.

For example, you write `print("Today is \(today)")`: should it print an 
Optional or should it print just the date, because it knows that it cannot be 
nil? I say it should print `.Optional(... 23:37)`. But what if it prints just 
the date? In this case `today` cannot be nil, so it would be safe to just print 
`23:37`. Now, I see the source code example for the first time. What thinking 
process do I have to go through to know if the variable is automatically 
unwrapped or not? I'll think "can this variable be nil at that place?" The 
compiler also thinks "can this variable be nil at that place?" Will the 
compiler and me always agree in this respect? Or do I have to think "Will the 
compiler think that the variable can be nil at this place? Can it decide that 
it can never be nil?"? In this case, the language user needs to have a mental 
model about what inferences the compiler is able to do, so the rules must be 
fixed and easily understandable. The model would probably be something along 
the lines of "NSDate() always returns a non-optional value, so `x ?? NSDate()` 
is non-optional too." But knowing that foo(3) will return a value because foo 
only returns nil if its argument is < 0 is probably out of scope, even if the 
foo-function is defined within the same source file and even if the `-O2` flag 
is turned on (because you don't want to have different semantics depending on 
how much optimization is turned on).

Therefore, I think it would be best to only apply implicit unwrapping in cases 
where the code would otherwise not compile.

E.g. now you have to write

var x: Int? = someFunction()
if(x == nil) { return 22 }
return x!+2+(2*x!);

It should be possible to rewrite this as

var x: Int? = someFunction()
if(x == nil) { return 22 }
return x+2+(2*x);

This should only work for variables defined within the same scope, so this 
should fail to compile:

// type of self.foo is String
if(self.foo == nil) { return 11 }
// type of myFunc is String -> ()
myFunc(self.foo)
  
because even though self.foo was non-nil 1 microsecond ago, it doesn't mean 
that it is non-nil now.

On the other hand, what happens if a variable is captured by a block? Do we 
know that the variable is not mutated from another thread? Should we disable 
all these rules as soon as there is a block somewhere that captures one of the 
variables and might mutate them?

I just started thinking... For all these reasons, I don't see how this is going 
to be implemented in a way that is consistent and that doesn't introduce all 
kinds of strange edge cases. And any solution should be comprehensible by a 
Swift-beginner IMHO. On the other hand, if I ever forget a "!" somewhere, and 
the compiler compiles it anyways because it knows that it is safe, I will not 
complain :)

-Michael

> Am 29.04.2016 um 16:37 schrieb Tod Cunningham via swift-evolution 
> :
> 
> I'm new to the swift evolution community, but I wanted to toss an idea out 
> there to get some feedback on it. So here it goes...
> 
> Currently, if you assign a non-nil value to an optional and then want to 
> access that optional later, in the same context, you need to manually unwrap 
> the value.  This is usually done either by using "!" or by using something 
> like "if let" or guard.
> 
> What would it be like if the compiler could auto unwrap, in cases where in 
> knows the optional will have some value?  This would make the code "clean" 
> and still be safe.
> 
> This concept of Auto Unwrapping of Optionals is similar to Implicitly 
> Unwrapped Optionals, but is only applied when the compiler knows it is safe 
> to do so.
> 
> Take the following example:
> 
> class Test {
>var today: NSDate? = nil
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as an optional
>let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow  // 
> Requires ! or (if let) to unwrap
>// ... do stuff with timeInterval ...
>}
> }
> 
> With the above example, the compiler could known that today has a value after 
> it's set in the test method.  So why couldn't the compiler auto unwrap it 
> when accessed?  This would mean manual unwrapping would be unnecessary:
> 
> class Test {
>var today: NSDate? = nil
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as a value (not an 
> optional)
>let timeInterval: NSTimeInterval = today.timeIntervalSinceNow  // No ! 
> required (auto unwrapped)
>// ... do stuff with timeInterval ...
>}
> }
> 
> If the value later gets set to an optional value, then it will no 

[swift-evolution] [Pitch] Reducing the bridging magic in dynamic casts

2016-04-29 Thread Joe Groff via swift-evolution
When we introduced Swift, we wanted to provide value types for common 
containers, with the safety and state isolation benefits they provide, while 
still working well with the reference-oriented world of Cocoa. To that end, we 
invested a lot of work into bridging between Swift’s value semantics containers 
and their analogous Cocoa container classes. This bridging consisted of several 
pieces in the language, the compiler, and the runtime:

Importer bridging, importing Objective-C APIs that take and return NSString, 
NSArray, NSDictionary and NSSet so that they take and return Swift’s analogous 
value types instead.

Originally, the language allowed implicit conversions in both directions 
between Swift value types and their analogous classes. We’ve been working on 
phasing the implicit conversions out—we removed the object-to-value implicit 
conversion in Swift 1.2, and propose to remove the other direction in 
SE–0072—but the conversions can still be performed by an explicit coercion 
string as NSString. These required-explicit as coercions don’t otherwise exist 
in the language, since as generally is used to force coercions that can also 
happen implicitly, and value-preserving conversions are more idiomatically 
performed by constructors in the standard library.

The runtime supports dynamic bridging casts. If you have a value that’s 
dynamically of a Swift value type, and try to as?, as!, or is-cast it to its 
bridged Cocoa class type, the cast will succeed, and the runtime will apply the 
bridging conversion:

// An Any that dynamically contains a value "foo": String
let x: Any = "foo"
// Cast succeeds and produces the bridged "foo": NSString
let y = x as! NSString 
Since Swift first came out, Cocoa has done a great job of “Swiftification”, 
aided by new Objective-C features like nullability and lightweight generics 
that have greatly improved the up-front quality of importer-bridged APIs. This 
has let us deemphasize and gradually remove the special case implicit 
conversions from the language. I think it’s time to consider extricating them 
from the dynamic type system as well, making it so that as?, as!, and is casts 
only concern themselves with typechecks, and transitioning to using standard 
initializers and methods for performing bridging conversions. I’d like to 
propose the following changes:

Dynamic casts as?, as! and is should no longer perform bridging conversions 
between value types and Cocoa classes.
Coercion syntax as should no longer be used to explicitly force certain 
bridging conversions.
To replace this functionality, we should add initializers to bridged value 
types and classes that perform the value-preserving bridging operations.
The Rules of as[?]

Our original goal implementing this behavior into the dynamic casting machinery 
was to preserve some transitivity identities between implicit conversions and 
casts that users could reason about, including:

x as! T as! U === x as! U, if x as! T succeeds. Casting to a type U should 
succeed and give the same result for any derived cast result.
x as! T as U === x as! U. If T is coercible to U, then you should get the same 
result by casting to Tand coercing to U as by casting to U directly.
x as T as! U === x as! U. Likewise, coercing shouldn’t affect the result of any 
ensuing dynamic casts.
x as T as U === x as U.
The interaction of these identities with the bridging conversions, as well as 
with other type system features like implicit nonoptional-to-Optional 
conversion, occasionally requires surprising behavior, for instance the 
behavior of nil Optional values in https://github.com/apple/swift/pull/1949. 
These rules also inform the otherwise-inconsistent use of as to perform 
explicit bridging conversions, when as normally only forces implicit 
conversions. By simplifying the scope of dynamic casts, it becomes easier to 
preserve these rules without bugs and unfortunate edge cases.

The Abilities of as? Today

In discussing how to change the behavior of dynamic casts, it’s worth 
enumerating all the things dynamic casts are currently able to do:

Check that an object is an instance of a specific class.

class Base {}; class Derived: Base {}

func isKindOfDerived(object: Base) -> Bool {
  return object is Derived
}

isKindOfDerived(object: Derived()) // true
isKindOfDerived(object: Base()) // false
Check that an existential contains an instance of a type.

protocol P {}
extension Int: P {}
extension Double: P {}

func isKindOfInt(value: P) -> Bool {
  return value is Int
}
isKindOfInt(value: 0) // true
isKindOfInt(value: 0.0) // false
Check that a generic value is also an instance of a different type.

func is(value: T, kindOf: U.Type) -> Bool {
  return value is U
}

is(value: Derived(), kindOf: Derived.self) // true
is(value: Derived(), kindOf: Base.self) // true
is(value: Base(), kindOf: Derived.self) // false
is(value: 0, kindOf: Int.self) // true
Check whether the type of a value conforms to a protocol, and 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Kevin Ballard via swift-evolution
On Thu, Apr 28, 2016, at 02:13 PM, Pyry Jahkola via swift-evolution wrote:
>> I would really like a different name for scan. While it’s the term of
>> art for Haskell and co, it really seems meaningless to regular
>> programmers (why is “scanning” the way you produce an array of
>> intermediate reduces?), and it would be better to follow the pattern
>> already established elsewhere in the library to give friendlier names
>> e.g. flatMap instead of bind, reduce instead of fold.
>>
>> I think Python calls it accumulate:
>> http://docs.python.org/3/library/itertools.html#itertools.accumulate
>
> FWIW, Clojure calls it `reductions[1]` which aligns pretty nicely with
> the `reduce` counterpart.
 
I like it.
 
-Kevin Ballard

Links:

  1. 
http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reductions
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Kevin Ballard via swift-evolution
On Thu, Apr 28, 2016, at 12:30 PM, Mark Lacey via swift-evolution wrote:
> I haven’t read through the complete proposal in detail, but regarding
> the ‘scan’ operation I would like to point out that the definition
> given in the example matches the semantics of what is usually called
> ‘prescan' or 'exclusive scan', whereas ‘scan’ (aka ‘inclusive scan’ or
> ‘prefix sum’) would not include the identity element, and each
> position of the result would include applying the operator to the
> elements up to and including the element in the same position of the
> source array, e.g.:
>
> (1..<6).scan(combine: +) // [1, 3, 6, 10, 15, 21]
>
> Sources:
> https://www.cs.cmu.edu/~guyb/papers/Ble93.pdf
> https://en.wikipedia.org/wiki/Prefix_sum
 
Interesting, I was not aware of the distinction here. The `scan` method
as proposed here matches the behavior of Haskell's `scanl` method
(http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:scanl)
.
 
I'm in favor of keeping the behavior as-is, because the "inclusive scan"
behavior can be recovered trivially by calling `.dropFirst()` on the
resulting sequence, whereas recovering prescan from inclusive scan is
not so trivial.
 
-Kevin Ballard
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Kevin Ballard via swift-evolution
On Thu, Apr 28, 2016, at 11:11 AM, Chris Lattner via swift-evolution wrote:
> Hello Swift community,
> 
> The review of "SE-0045: Add scan, prefix(while:), drop(while:), and iterate 
> to the stdlib" begins now and runs through May 3. The proposal is available 
> here:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0045-scan-takewhile-dropwhile.md

The proposal has been updated as per feedback from the core team 
(https://github.com/apple/swift-evolution/pull/275). This includes removing 
some last vestiges of Swift 2 naming as well as replacing `iterate(_:apply:)` 
with an overloaded function `unfold(_:applying:)`.

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


Re: [swift-evolution] [Proposal] Add Binary Search functions to SequenceType

2016-04-29 Thread Dave Abrahams via swift-evolution

on Fri Apr 29 2016, Haravikk  wrote:

> Actually, the binary search proposal settled on a definition of a partition
> point method (and probably a partition method as well) that provides the real
> implementation details anyway, so these could go ahead as-is. 

That's what I had in mind.

> You’re right that the search methods themselves may prefer to wait,
> since .sort() will likely change to reflect the new strict ordering
> operator, in which case it makes sense to delay those to be
> consistent, but partitioning should be unaffected.
>
> On 28 Apr 2016, at 13:03, Jeff Hajewski via swift-evolution
>  wrote:
>
> Thanks for bringing this back into the spotlight Pyry. A few of us have 
> been
> working on this issue here:
>
> https://github.com/lorenzoracca/Swift-binary-search
>
> However we have sort of stalled as we have been unable to come up with a
> unary approach that Dave suggested using just Bool return values. And of
> course, as you say, the three case order enum would make this a trivial
> problem.
>
> I guess the question is, do we move forward without a unary implementation
> and update if/when we get a three case Order enum or do we wait on a three
> case Order enum and implement a fully generic version once?
>
> Jeff
>
> On Thu, Apr 28, 2016 at 7:36 AM, Pyry Jahkola
>  wrote:
>
> Bringing up this topic because it became relevant with Brent
> Royal-Gordon's "[Idea] Bringing the partial/total ordering distinction
> into Comparable".
>
> If the `<=>` operator with a return type of a three-case `enum Order`,
> you can fully define the most generic versions of binary searches as:
>
> lowerBound(compare: Self.Collection.Element -> Order) -> Index
>
> etc.
>
> On 29 Mar 2016, at 13:43, Jeff Hajewski via swift-evolution
>  wrote:
>
> I've responded below, but just for the sake of being explicit, 
> this
> is roughly 
> the signature for lowerBound, upperBound, and binarySearch I have 
> in 
> mind based on your comments of a unary predicate:
>
> lowerBound(isOrderedBelow: Self.Collection.Element -> Bool) -> 
> Index
> upperBound(isOrderedBelow: Self.Collection.Element -> Bool) -> 
> Index
> binarySearch(isOrderedBelow: Self.Collection.Element -> Bool) ->
> Bool
>
> That's the general structure - the key is that the exact same
> predicate is
> used in all signatures. The predicate would be defined along the
> lines of
> a binary predicate where one of the parameters is fixed as the
> search value.
> The unary predicate could be formed along the lines of:
>
> let binaryPred = { $0 < $1 }
> let unnaryPred = binaryPred($0, value)
>
> where value is the search value. The main point of illustrating 
> that
> is that
> once the unary predicate is defined, we can't change the position 
> of
> the
> search value within the predicate like they do in the C++
> implementation.
>
> You're right, there's no way a Bool-returning unary comparator could
> allow you to implement anything but lowerBound. With a three-value
> result, however, you've got all you need.
>
> I've shamelessly plugged before but for the sake of proving a point,
> I'll do it once more: I think this little library we did works as a 
> good
> starting point for a stdlib binary search API:
> 
> https://github.com/knomi/Allsorts/blob/master/Allsorts/BinarySearch.swift
>
> — Pyry
>
> ___
> 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

-- 
Dave

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


Re: [swift-evolution] [Proposal] Add Binary Search functions to SequenceType

2016-04-29 Thread Dave Abrahams via swift-evolution

on Thu Apr 28 2016, Jeff Hajewski  wrote:

> Dave - I think it boils down to a gap in communication. We were under the
> impression that the goal was a pure extension of CollectionType, without 
> making
> any requirements on Generator.Element (i.e., your requiring it to be
> comparable), where binary search, lower bound, and upper bound all work with 
> the
> same unary predicate. 
> Of course, as you demonstrated, it is trivial to implement when
> Generator.Element is Comparable, but if you relax that requirement it
> is not possible to create a set of functions (binary search, lower
> bound, upper bound) that all take the same unary predicate. 

I'm sorry if I gave you the wrong impression.  What I posted was exactly
what I had in mind.

> We ultimately came up with a slightly different approach, implementing
> binary search similar to your example, but a different take on lower
> bound, upper bound, and range. I suppose we should just send out our
> proposal and get everyone's take on it.
>
> Jeff
>
> On Thu, Apr 28, 2016 at 5:06 PM, Dave Abrahams via swift-evolution
>  wrote:
>
> on Thu Apr 28 2016, Jeff Hajewski
>  wrote:
>
> > Thanks for bringing this back into the spotlight Pyry. A few of us have
> been
> > working on this issue here:
> >
> > https://github.com/lorenzoracca/Swift-binary-search
> >
> > However we have sort of stalled as we have been unable to come up with a
> unary
> > approach that Dave suggested using just Bool return values. And of 
> course,
> as
> > you say, the three case order enum would make this a trivial problem.
> >
> > I guess the question is, do we move forward without a unary 
> implementation
> and
> > update if/when we get a three case Order enum or do we wait on a three
> case
> > Order enum and implement a fully generic version once?
>
> Or you could just do it like this (Swift 2.2-compatible). Am I missing
> something?
>
> extension CollectionType {
> /// Returns the index of the first element satisfying `predicate`,
> /// or `endIndex` if no such element exists.
> ///
> /// - Requires: `self` is partitioned with respect to `predicate`;
> /// that is, there exists an index `i` in `startIndex...endIndex`
> /// such that `predicate` returns `false` for every element of
> /// `self[startIndex.. /// of `self[i.. @warn_unused_result
> public func binarySearch(
> predicate: (Self.Generator.Element)->Bool
> ) -> Index {
> var len = count
> var min = startIndex
> while len > 0 {
> let half = len/2
> let middle = min.advancedBy(half)
>
> if !predicate(self[middle]) {
> min = middle.successor()
> len -= half.successor()
> } else {
> len = half
> }
> }
> return min
> }
> }
>
> extension CollectionType where Generator.Element : Comparable {
> /// Returns the index of the first element greater than or equal to
> /// `target`, or `endIndex` if no such element exists.
> ///
> /// - Requires: `self` is sorted.
> @warn_unused_result
> public func lowerBound(target: Self.Generator.Element) -> Index {
> return binarySearch { $0 >= target }
> }
>
> /// Returns the index of the first element greater than
> /// `target`, or `endIndex` if no such element exists.
> ///
> /// - Requires: `self` is sorted.
> @warn_unused_result
> public func upperBound(target: Self.Generator.Element) -> Index {
> return binarySearch { $0 > target }
> }
> }
>
> //===--- TEST IT -
> -===//
> import Darwin
> for _ in 0..<1000 {
> // build a sorted array of up to 30 values in the range 0..<10
> var a : Array = []
> for _ in 0.. a.append(Int(arc4random_uniform(10)))
> }
> a.sortInPlace()
>
> print(a)
>
> for i in -3...14 {
> let l = a.lowerBound(i)
> let u = a.upperBound(i)
> assert(l >= 0)
> assert(u <= a.count)
> assert(l <= u)
> if l > 0 {
> assert(a[l - 1] < i)
> }
> if l < a.count {
> assert(a[l] >= i)
> }
> if u > 0 {
> assert(a[u - 1] <= i)
> }
> if u < a.count {
> assert(a[u] > i)
> }
> }
> }
>
> --
> Dave
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-- 
Dave

___
swift-evolution mailing list
swift-evolution@swift.org

Re: [swift-evolution] Protocol non-conformance clause

2016-04-29 Thread Thorsten Seitz via swift-evolution

> Am 29.04.2016 um 19:51 schrieb Xiaodi Wu :
> 
> Yes, certainly this works today. The motivation for Erica's question is that 
> this would not work without modifying the third-party code if keywords were 
> required to indicate implementation of protocol requirements.

If I understood the motivation correctly, the requirements should protect 
against typos where I planned to *replace* a method but due to a typo instead 
created a new method and inherited the default (or superclass) implementation.
But this use case does not apply to modeling after the fact, because I simply 
*cannot make typos* there as the type to be extended in general is a third 
party type and cannot be edited by me.
Therefore extensions declaring conformance of a type to a protocol should not 
require any special markup for methods existing elsewhere (i.e. already in the 
type or other extensions of that type). 
But requiring `override` markers for new methods written within the extension 
would still be sensible because these would again protect against typos in my 
own code.

In addition some people like to split their types in parts writing them as 
extensions, e.g. one for each protocol conformance. This looks quite similar to 
modeling after the fact and the same rationale applies: requiring `override` 
markers within the extension make sense.

So we would have:

// third party code; using split declarations

struct ThirdPartyProtocol {
func bar()
}

struct ThirdParty { 
func foo() { … }
}

extension ThirdParty : ThirdPartyProtocol {
override func bar() { … } // `override` marker required
}

// my code: modeling after the fact

protocol A { 
func foo() 
func baz()
}

extension ThirdParty : A {
// no markers required for foo()  
override func baz() { … } // `override` marker required
}


> One possible solution might emerge if it is possible to extend a protocol 
> conditional on Self not being some concrete type. Thus, asking whether there 
> is a way to express that.

I do not see the need for that. This sounds like introducing something together 
with a workaround for it :-)
But maybe I have misunderstood what you intend.

-Thorsten



> On Fri, Apr 29, 2016 at 12:45 Thorsten Seitz  > wrote:
> No problem, that still works, because the most specific implementation is 
> chosen:
> 
> protocol A { func foo()}
> protocol B {} // empty protocol
> 
> extension A  {
> func foo() {
> print("Self is A")
> }
> }
> 
> extension A where Self: B {
> func foo() {
> print("Self is B")
> }
> }
> 
> // Works
> struct S1: A, B {}
> S1().foo() // Self is B
> 
> struct S2: A {}
> S2().foo() // Self is A
> 
> 
> // Wu's example works, too
> 
> struct ThirdParty {
> func foo() {
> print("Self is ThirdParty")
> }
> }
> 
> extension ThirdParty : A {}
> 
> ThirdParty().foo() // Self is ThirdParty
> 
> 
> // dynamic dispatch works, too
> 
> let a1: A = S1()
> a1.foo() // Self is B
> 
> let a2: A = S2()
> a2.foo() // Self is A
> 
> let a3: A = ThirdParty() // Self is ThirdParty
> a3.foo()
> 
> 
> -Thorsten
> 
> 
>> Am 29.04.2016 um 17:20 schrieb Erica Sadun > >:
>> 
>> In Wux's example, he has third party code:
>> 
>> ```
>> Type ThirdParty {
>> func foo() { print("from third party") }
>> }
>> ```
>> 
>> Then in his own code, he defines protocol A and extends it:
>> 
>> extension A {
>> func foo() {
>> print("Self is B")
>> }
>> }
>> 
>> and conforms ThirdParty to A. But he wants the original  foo() 
>> implementation. Your approach
>> for writing an extension for plain A without a where clause doesn't offer 
>> that solution. The goal
>> here is "Add this default behavior *only* where a type does not conform to B"
>> 
>> -- E
>> 
>> 
>>> On Apr 29, 2016, at 9:10 AM, Thorsten Seitz >> > wrote:
>>> 
>>> Just writing an extension for plain A without a where clause works.
>>> 
>>> -Thorsten 
>>> 
>>> Am 29.04.2016 um 16:03 schrieb Erica Sadun via swift-evolution 
>>> >:
>>> 
 Gmane is down as far as my browser is concerned and I haven't found 
 anything by Googling.
 
 Given the following:
 
 protocol A {func foo()}
 protocol B {} // empty protocol
 
 extension A where Self:B {
 func foo() {
 print("Self is B")
 }
 }
 
 // Works
 struct S1: A, B {}
 S1().foo()
 
 Is there a way to produce a similar extension that exempts any type that 
 conforms to B?
 
 cc'ing in Wux because this is a direct response to a scenario he brought 
 up yesterday.
 
 -- E
 
 ___
 swift-evolution mailing list
 swift-evolution@swift.org 

Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0067: Enhanced Floating Point Protocols

2016-04-29 Thread Dave Abrahams via swift-evolution

on Tue Apr 26 2016, Tony Allevato  wrote:

> On 2016-04-26 22:32:16 +, Dave Abrahams via swift-evolution said:
>
>> The main reasons to route through a single generic operator
>> implementation are:
>>
>> * User experience; we want to cut down the number of overloads of any
>>   operator to a manageable set, in part because they live in the global
>>   namespace.  When you look at a list of functions in the global
>>   namespace, seeing fifty instances of `func +` is not helpful.
>>
>> * Type checker speed.  Having all of these overloads around has
>>   historically put a strain on the type checker and made compilation
>>   slow.  That may be less true today than it once was, though.
>
> These are both completely understandable concerns (especially the type
> checker speed, since I've hit the "expression too complex" problem in
> a couple odd places myself). I'm hoping though that we can converge on
> a solution other than "pollute the public interface of a type with
> named methods that duplicate the operators, which are trampolines to
> those methods", since I think that actually detracts from the user
> experience of using that type.
>
> Would something like this be possible? Imagine protocols defined like this:
>
>public protocol Equatable {
>static func == (lhs: Self, rhs: Self) -> Self
>}
>public protocol FloatingPoint: Equatable {
>static func + (lhs: Self, rhs: Self) -> Self
>}
>
> This would have the effect of automatically generating the following
> generic trampoline global operators:
>
>public func == (lhs: T, rhs: T) -> T {
>return T.==(lhs, rhs)
>}
>public func + (lhs: T, rhs: T) -> T {
>return T.+(lhs, rhs)
>}
>
> Then, types that conform to FloatingPoint would define the method as
> appropriate:
>
>public struct Double: FloatingPoint {
>public static func == (lhs: Double, rhs: Double) -> Double { ... }
>public static func + (lhs: Double, rhs: Double) -> Double { ... }
>}
>
> If something like this worked, it has a number of advantages:
>
> * It has the same lower overhead with respect to the global namespace
> as the currently proposed strategy that uses an explicitly defined
> generic operator that trampolines to a named add() method. This should
> keep type checking fast and keeps the number of global instances of
> the operator low.
> * It increases consistency: the operator requirement is declared in
> the protocol, and the concrete implementation is *in* the conforming
> type (as opposed to a separate global function).
> * There is no need to introduce arbitrarily named methods to implement
> the operations that would pollute the public interface of the type.
> * It doesn't affect the ability to pass operators as first-class
> functions into other algorithms (like + into reduce). In fact, if an
> algorithm needs to be explicit about the types (if they can't be
> inferred for some reason), then for example `Float.+` would refer to
> the appropriate `(Float, Float) -> Float` function.
>
> Some might argue that implicitly defining the generic global operator
> under the covers is a drawback to this approach, but I think that's a
> minor concern when weighed against the alternatives.
>
> Individual elements of the syntax could be debated (an "operator"
> keyword instead of "static func"? But that might just be syntactic
> sugar), but overall, I'd love to get feedback on the feasibility of an
> approach like this. I'm happy to take a stab at drawing this up in a
> proposal, as well.

Hi Tony,

As you can see in the notes from April 27, 2016 language review, the
core team discussed this.  Although one member had some reservations, I
think it would be very worthwhile for you to write the proposal that
allows static operator methods, and soon.  In Swift 3, we think the
trampolines have to be manual, rather than automatically-generated, and
we are unsure that automatic generation can work at all, so I strongly
recommend that you take up that possibility in a follow-on proposal if
you think it's important.

Thanks for the great idea!

-- 
Dave

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


Re: [swift-evolution] Auto Unwrapping Of Optionals

2016-04-29 Thread Tod Cunningham via swift-evolution
Adrian, excellent example of a challenging case.  I would say that when calling 
any method that might mutate the value, the compiler would no longer be able to 
safely auto unwrap.  That really limits the usefulness of this capability, at 
least for classes. For classes that would mean any call that would leave the 
current context would disable the auto unwrapping. For structs, it would be any 
mutating method would disable the auto unwrap.

I modified my example a bit to show how this would effect the ability to auto 
unwrap.

class Test {
  var today: NSDate? = nil

  func test() {
 today = today ?? NSDate()
 let timeInterval: NSTimeInterval = today.timeIntervalSinceNow // No ! 
required (auto unwrapped)

 // today can no longer be auto unwrapped as calling timeIntervalSinceNow 
has escaped
 // the enclosing context and could cause side effects with this instance.
}

It would be nice if the compiler could know that timeIntervalSinceNow had no 
dependencies or knowledge of class Test, but I doubt that would be practical.

However if Test was a struct the mutation information is readily available, so 
we know these calls would be safe:

struct Test {
var today: NSDate? = nil

mutating func test() {
today = today ?? NSDate()
let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow // No ! 
required (auto unwrapped)
let timeInterval2: NSTimeInterval = today!.timeIntervalSinceNow // 
Explicit unwrapping would still be allowed
print("Today is \(today)") // Would be printed as a value (not an 
optional)

// today can still be auto unwrapped as it won't be mutated by 
timeIntervalSinceNow or print
}
}


From: 
> 
on behalf of Adrian Zubarev via swift-evolution 
>
Reply-To: Adrian Zubarev 
>
Date: Friday, April 29, 2016 at 3:21 PM
To: "swift-evolution@swift.org" 
>
Subject: Re: [swift-evolution] Auto Unwrapping Of Optionals

+1 But your example is too good to be true. :)

What would happen to this code:

class A {

var value: Type? = nil

func reset() { self.value = nil }

func test() {

self.value = self.value ?? Type()

self.reset()

self.value.doSomething()

// can the compiler be sure that our value wasn't reset somewhere from 
a different scope ?
 }
}

I'm curious what will happen here. Can someone clarify on that?

--
Adrian Zubarev

Am 29. April 2016 um 16:37:37, Tod Cunningham via swift-evolution 
(swift-evolution@swift.org) schrieb:

I'm new to the swift evolution community, but I wanted to toss an idea out 
there to get some feedback on it. So here it goes...

Currently, if you assign a non-nil value to an optional and then want to access 
that optional later, in the same context, you need to manually unwrap the 
value. This is usually done either by using "!" or by using something like "if 
let" or guard.

What would it be like if the compiler could auto unwrap, in cases where in 
knows the optional will have some value? This would make the code "clean" and 
still be safe.

This concept of Auto Unwrapping of Optionals is similar to Implicitly Unwrapped 
Optionals, but is only applied when the compiler knows it is safe to do so.

Take the following example:

class Test {
var today: NSDate? = nil
func test() {
today = today ?? NSDate()
print("Today is \(today)") // Would be printed as an optional
let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow // Requires ! or 
(if let) to unwrap
// ... do stuff with timeInterval ...
}
}

With the above example, the compiler could known that today has a value after 
it's set in the test method. So why couldn't the compiler auto unwrap it when 
accessed? This would mean manual unwrapping would be unnecessary:

class Test {
var today: NSDate? = nil
func test() {
today = today ?? NSDate()
print("Today is \(today)") // Would be printed as a value (not an optional)
let timeInterval: NSTimeInterval = today.timeIntervalSinceNow // No ! required 
(auto unwrapped)
// ... do stuff with timeInterval ...
}
}

If the value later gets set to an optional value, then it will no longer be 
auto unwrapable :

class Test {
var today: NSDate? = nil

func optionalDay() -> NSDate? {
return NSDate()
}

func test() {
today = today ?? NSDate()
print("Today is \(today)") // Would be printed as a value (not an optional)
let timeInterval: NSTimeInterval = today.timeIntervalSinceNow // No ! required 
(auto unwrapped)
let timeInterval2: NSTimeInterval = today!.timeIntervalSinceNow // Explicit 
unwrapping would still be allowed

// If today is assigned an optional value, we can no longer auto unwrap it
today = optionalDay()

Re: [swift-evolution] Eliminate inconsistencies among primary collection types

2016-04-29 Thread Xiaodi Wu via swift-evolution
On Fri, Apr 29, 2016 at 2:49 PM, Nate Cook via swift-evolution <
swift-evolution@swift.org> wrote:

> > On Apr 29, 2016, at 1:57 PM, Wolfgang H. via swift-evolution <
> swift-evolution@swift.org> wrote:
> >
> > Inconsistency A. is that “Set” currently is the only collection type
> conforming to protocol 'Hashable'”. IMHO both “Array” and “Dictionary”
> should conform to protocol “Hashable”, too.
>
> Set is the only Hashable* collection type because it's the only collection
> type where all of its values are always Hashable themselves. Array
> can be an array of a non-Hashable type; Dictionary can have a
> non-Hashable type for Value. If/when Swift gains conditional protocol
> compliance, arrays and dictionaries of Hashable types could themselves be
> Hashable, but not until then.
>
> > Inconsistency B. is that “Array” is typesafe if used as element of
> an “Array” but is non-typesafe if used as element of “Set” or “Dictionary”.
> The non-typesafety may result from the mapping of “Array” to “NSArray“.
>
> Since Array isn't Hashable, you can't create a Set.
> The type system therefore falls back to using the bridged Objective-C type
> for Array, which can provide a hash value based on object identity.
>
> Nate
>
>
> *For my spell checker's sake, could we rename Hashable to Washable? Thanks



Well put, Nate.
It will be a great day when conditional protocol compliance comes to Swift.
Until then, there's good reason why Array and Dictionary can't be washed.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Eliminate inconsistencies among primary collection types

2016-04-29 Thread Nate Cook via swift-evolution
> On Apr 29, 2016, at 1:57 PM, Wolfgang H. via swift-evolution 
>  wrote:
> 
> Inconsistency A. is that “Set” currently is the only collection type 
> conforming to protocol 'Hashable'”. IMHO both “Array” and “Dictionary” should 
> conform to protocol “Hashable”, too.

Set is the only Hashable* collection type because it's the only collection type 
where all of its values are always Hashable themselves. Array can be 
an array of a non-Hashable type; Dictionary can have a non-Hashable 
type for Value. If/when Swift gains conditional protocol compliance, arrays and 
dictionaries of Hashable types could themselves be Hashable, but not until then.

> Inconsistency B. is that “Array” is typesafe if used as element of an 
> “Array” but is non-typesafe if used as element of “Set” or “Dictionary”. The 
> non-typesafety may result from the mapping of “Array” to “NSArray“.

Since Array isn't Hashable, you can't create a Set. The 
type system therefore falls back to using the bridged Objective-C type for 
Array, which can provide a hash value based on object identity.

Nate


*For my spell checker's sake, could we rename Hashable to Washable? Thanks

> - - - Wolfgang H.
> 
> 
>> Am 2016-04-29 17/Fr um 20:18 schrieb Xiaodi Wu - xiaodi...@gmail.com:
>> 
>> I'm not sure I understand the inconsistency you see. Set and Dictionary 
>> require hashable values and keys, respectively. That's just in the nature of 
>> what these types are. Do you want Set itself to conform to Hashable?
>> 
>> On Fri, Apr 29, 2016 at 12:57 Wolfgang H. via swift-evolution 
>>  wrote:
>> 
>> A. When trying to declare nested collection types an inconsistency
>>  is unveiled:
>> 
>> 
>> A.1. “Array” as outer type allows for every collection type as inner
>>type (“Int” used as a placeholder for “some other type”):
>> 
>>   let test_aa: Array = []
>>   // ok
>> 
>>   let test_as: Array = []
>>   // ok
>> 
>>   let test_ad: Array> = []
>>   // ok
>> 
>> 
>> A.2. “Set” as outer type allows for “Set” as inner type only:
>> 
>>   let test_sa: Set = []
>>   // compile time error “Type 'Array' does not conform to
>>   // protocol 'Hashable'”
>> 
>>   let test_ss: Set = []
>>   // ok
>> 
>>   let test_sd: Set> = []
>>   // compile time error “Type 'Dictionary' does not
>>   // conform to protocol 'Hashable'”
>> 
>> 
>> A.3. The same is true for “Dictionary” as outer type:
>> 
>>   let test_da: Dictionary = [:]
>>   // compile time error “Type 'Array' does not conform to
>>   // protocol 'Hashable'”
>> 
>>   let test_ds: Dictionary = [:]
>>   // ok
>> 
>>   let test_dd: Dictionary, Int> = [:]
>>   // compile time error “Type 'Dictionary' does not
>>   // conform to protocol 'Hashable'”
>> 
>> 
>> B. When letting Swift infer the type of collections of “Array” from
>>  literals another inconsistency comes to light:
>> 
>> 
>> B.1. “Array” as outer type behaves IMHO perfectly:
>> 
>>   var testArray = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
>>   print(testArray.dynamicType)
>>   // prints “Array”
>>   testArray.append( [ 1, "five", 25, 625 ] );
>>   // compile time error “Cannot convert value of 'String' to
>>   // expected element type 'Int'”; type safe
>> 
>> 
>> B.2. “Set” as outer type works but there is no type safety:
>> 
>>   var testSet: Set = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
>>   print(testSet.dynamicType)
>>   // prints “Set”
>>   testSet.insert( [ 1, "five", 25, 625 ] )
>>   // neither run time nor compile time errors; no type safety
>> 
>> 
>> B.3. The same goes for “Dictionary” as outer type:
>> 
>>   var testDictionary = [
>>   [ 1, 2, 4, 8 ]: "Powers of Two",
>>   [ 1, 3, 9, 27 ]: "Powers of Three",
>>   ]
>>   print(testDictionary.dynamicType)
>>   // prints "Dictionary"
>>   testDictionary[ [ 1, "five", 25, 625 ] ] = "Powers of Five"
>>   // neither run time nor compile time errors; no type safety
>> 
>> 
>> 
>> — — - Wolfgang H.
>> 
>> 
>> ___
>> 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] Auto Unwrapping Of Optionals

2016-04-29 Thread Adrian Zubarev via swift-evolution
+1 But your example is too good to be true. :)  

What would happen to this code:  

class A {  

 var value: Type? = nil  

 func reset() { self.value = nil }  

 func test() {  

 self.value = self.value ?? Type()  

 self.reset()  

 self.value.doSomething()  

 // can the compiler be sure that our value wasn't reset somewhere from a 
different scope ?  
 }
}

I'm curious what will happen here. Can someone clarify on that?  

--  
Adrian Zubarev  

Am 29. April 2016 um 16:37:37, Tod Cunningham via swift-evolution 
(swift-evolution@swift.org(mailto:swift-evolution@swift.org)) schrieb:

>  
> I'm new to the swift evolution community, but I wanted to toss an idea out 
> there to get some feedback on it. So here it goes...
>  
> Currently, if you assign a non-nil value to an optional and then want to 
> access that optional later, in the same context, you need to manually unwrap 
> the value. This is usually done either by using "!" or by using something 
> like "if let" or guard.
>  
> What would it be like if the compiler could auto unwrap, in cases where in 
> knows the optional will have some value? This would make the code "clean" and 
> still be safe.
>  
> This concept of Auto Unwrapping of Optionals is similar to Implicitly 
> Unwrapped Optionals, but is only applied when the compiler knows it is safe 
> to do so.
>  
> Take the following example:
>  
> class Test {
> var today: NSDate? = nil
> func test() {
> today = today ?? NSDate()
> print("Today is \(today)") // Would be printed as an optional
> let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow // Requires ! 
> or (if let) to unwrap
> // ... do stuff with timeInterval ...
> }
> }
>  
> With the above example, the compiler could known that today has a value after 
> it's set in the test method. So why couldn't the compiler auto unwrap it when 
> accessed? This would mean manual unwrapping would be unnecessary:
>  
> class Test {
> var today: NSDate? = nil
> func test() {
> today = today ?? NSDate()
> print("Today is \(today)") // Would be printed as a value (not an optional)
> let timeInterval: NSTimeInterval = today.timeIntervalSinceNow // No ! 
> required (auto unwrapped)
> // ... do stuff with timeInterval ...
> }
> }
>  
> If the value later gets set to an optional value, then it will no longer be 
> auto unwrapable :
>  
> class Test {
> var today: NSDate? = nil
>  
> func optionalDay() -> NSDate? {
> return NSDate()
> }
>  
> func test() {
> today = today ?? NSDate()
> print("Today is \(today)") // Would be printed as a value (not an optional)
> let timeInterval: NSTimeInterval = today.timeIntervalSinceNow // No ! 
> required (auto unwrapped)
> let timeInterval2: NSTimeInterval = today!.timeIntervalSinceNow // Explicit 
> unwrapping would still be allowed
>  
> // If today is assigned an optional value, we can no longer auto unwrap it
> today = optionalDay()
> print("Today is \(today)") // Would be printed as an optional
> let timeInterval3: NSTimeInterval = today!.timeIntervalSinceNow // manual 
> unwrapping would be required
> }
> }
>  
> Note in the above example, explicit unwrapping would still be allow. The 
> variable is still an optional. This allows for existing code to remain 
> unchanged.
>  
> This change would encourage less use of forced unwrapping "!", generally 
> require the developer to write less code, and would maintain code safety. On 
> the down side, it is performing some compiler “magic”. It would be yet 
> another thing to explain when trying to introduce people to swift and 
> especially optionals.
>  
> What do you all think, would something like this be worth pursuing, what 
> other pluses or minus would this introduce, has something like this already 
> been discussed?
>  
> Thanks,
> Tod Cunningham
>  
> ___
> 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] Eliminate inconsistencies among primary collection types

2016-04-29 Thread Wolfgang H. via swift-evolution
Inconsistency A. is that “Set” currently is the only collection type conforming 
to protocol 'Hashable'”. IMHO both “Array” and “Dictionary” should conform to 
protocol “Hashable”, too.

Inconsistency B. is that “Array” is typesafe if used as element of an 
“Array” but is non-typesafe if used as element of “Set” or “Dictionary”. The 
non-typesafety may result from the mapping of “Array” to “NSArray“.

- - - Wolfgang H.


> Am 2016-04-29 17/Fr um 20:18 schrieb Xiaodi Wu - xiaodi...@gmail.com:
> 
> I'm not sure I understand the inconsistency you see. Set and Dictionary 
> require hashable values and keys, respectively. That's just in the nature of 
> what these types are. Do you want Set itself to conform to Hashable?
> 
> On Fri, Apr 29, 2016 at 12:57 Wolfgang H. via swift-evolution 
>  wrote:
> 
> A. When trying to declare nested collection types an inconsistency
>   is unveiled:
> 
> 
> A.1. “Array” as outer type allows for every collection type as inner
> type (“Int” used as a placeholder for “some other type”):
> 
>let test_aa: Array = []
>// ok
> 
>let test_as: Array = []
>// ok
> 
>let test_ad: Array> = []
>// ok
> 
> 
> A.2. “Set” as outer type allows for “Set” as inner type only:
> 
>let test_sa: Set = []
>// compile time error “Type 'Array' does not conform to
>// protocol 'Hashable'”
> 
>let test_ss: Set = []
>// ok
> 
>let test_sd: Set> = []
>// compile time error “Type 'Dictionary' does not
>// conform to protocol 'Hashable'”
> 
> 
> A.3. The same is true for “Dictionary” as outer type:
> 
>let test_da: Dictionary = [:]
>// compile time error “Type 'Array' does not conform to
>// protocol 'Hashable'”
> 
>let test_ds: Dictionary = [:]
>// ok
> 
>let test_dd: Dictionary, Int> = [:]
>// compile time error “Type 'Dictionary' does not
>// conform to protocol 'Hashable'”
> 
> 
> B. When letting Swift infer the type of collections of “Array” from
>   literals another inconsistency comes to light:
> 
> 
> B.1. “Array” as outer type behaves IMHO perfectly:
> 
>var testArray = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
>print(testArray.dynamicType)
>// prints “Array”
>testArray.append( [ 1, "five", 25, 625 ] );
>// compile time error “Cannot convert value of 'String' to
>// expected element type 'Int'”; type safe
> 
> 
> B.2. “Set” as outer type works but there is no type safety:
> 
>var testSet: Set = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
>print(testSet.dynamicType)
>// prints “Set”
>testSet.insert( [ 1, "five", 25, 625 ] )
>// neither run time nor compile time errors; no type safety
> 
> 
> B.3. The same goes for “Dictionary” as outer type:
> 
>var testDictionary = [
>[ 1, 2, 4, 8 ]: "Powers of Two",
>[ 1, 3, 9, 27 ]: "Powers of Three",
>]
>print(testDictionary.dynamicType)
>// prints "Dictionary"
>testDictionary[ [ 1, "five", 25, 625 ] ] = "Powers of Five"
>// neither run time nor compile time errors; no type safety
> 
> 
> 
> — — - Wolfgang H.
> 
> 
> ___
> 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] Eliminate inconsistencies among primary collection types

2016-04-29 Thread Haravikk via swift-evolution
The only way to do this would be to require a hashing closure as an alternative 
to requiring Hashable, which is certainly do-able, but would be just as 
inconsistent.

I think the real problem is that Set and Dictionary are just types, but really 
they should conform to some kind of protocol instead, as it’s entirely 
conceivable to want to implement a key/value type that uses a tree structure 
for storage, in which case Hashable isn’t a requirement (but Comparable might 
be).

The solution therefore is to define general purpose Set and Map protocols, and 
maybe rename Set to HashSet or something, so that we have a similar distinction 
as is the case between CollectionType (protocol) and Array (implementing type). 
I’ve been trying to do this retroactively to implement some specialised 
map-types, but it leads to all kinds of compiler issues since Dictionary is 
being extended in a somewhat unusual way, I expect Set might have similar 
issues, so it would be better if the protocols were official.

> On 29 Apr 2016, at 18:57, Wolfgang H. via swift-evolution 
>  wrote:
> 
> 
> A. When trying to declare nested collection types an inconsistency
>   is unveiled:
> 
> 
> A.1. “Array” as outer type allows for every collection type as inner
> type (“Int” used as a placeholder for “some other type”):
> 
>let test_aa: Array = []
>// ok
> 
>let test_as: Array = []
>// ok
> 
>let test_ad: Array> = []
>// ok
> 
> 
> A.2. “Set” as outer type allows for “Set” as inner type only:
> 
>let test_sa: Set = []
>// compile time error “Type 'Array' does not conform to 
>// protocol 'Hashable'”
> 
>let test_ss: Set = []
>// ok
> 
>let test_sd: Set> = []
>// compile time error “Type 'Dictionary' does not 
>// conform to protocol 'Hashable'”
> 
> 
> A.3. The same is true for “Dictionary” as outer type:
> 
>let test_da: Dictionary = [:]
>// compile time error “Type 'Array' does not conform to 
>// protocol 'Hashable'”
> 
>let test_ds: Dictionary = [:]
>// ok
> 
>let test_dd: Dictionary, Int> = [:]
>// compile time error “Type 'Dictionary' does not 
>// conform to protocol 'Hashable'”
> 
> 
> B. When letting Swift infer the type of collections of “Array” from
>   literals another inconsistency comes to light:
> 
> 
> B.1. “Array” as outer type behaves IMHO perfectly:
> 
>var testArray = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
>print(testArray.dynamicType)
>// prints “Array”
>testArray.append( [ 1, "five", 25, 625 ] );
>// compile time error “Cannot convert value of 'String' to
>// expected element type 'Int'”; type safe
> 
> 
> B.2. “Set” as outer type works but there is no type safety:
> 
>var testSet: Set = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
>print(testSet.dynamicType)
>// prints “Set”
>testSet.insert( [ 1, "five", 25, 625 ] )
>// neither run time nor compile time errors; no type safety
> 
> 
> B.3. The same goes for “Dictionary” as outer type:
> 
>var testDictionary = [
>[ 1, 2, 4, 8 ]: "Powers of Two",
>[ 1, 3, 9, 27 ]: "Powers of Three",
>]
>print(testDictionary.dynamicType)
>// prints "Dictionary"
>testDictionary[ [ 1, "five", 25, 625 ] ] = "Powers of Five"
>// neither run time nor compile time errors; no type safety
> 
> 
> 
> — — - Wolfgang H.
> 
> 
> ___
> 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] Auto Unwrapping Of Optionals

2016-04-29 Thread Haravikk via swift-evolution
This is definitely something I’m hoping to see as well, alongside more 
intelligent handling of the is keyword, as currently Swift doesn’t handle the 
following either:

if foo is SomeType { /* foo could be safely used as SomeType here, but 
currently is not */ }

Hopefully someone more familiar can weigh in, as it seems like something I 
expect to be on the way but perhaps has been delayed in case any further 
changes to the type system were required?

> On 29 Apr 2016, at 15:37, Tod Cunningham via swift-evolution 
>  wrote:
> 
> I'm new to the swift evolution community, but I wanted to toss an idea out 
> there to get some feedback on it. So here it goes...
> 
> Currently, if you assign a non-nil value to an optional and then want to 
> access that optional later, in the same context, you need to manually unwrap 
> the value.  This is usually done either by using "!" or by using something 
> like "if let" or guard.
> 
> What would it be like if the compiler could auto unwrap, in cases where in 
> knows the optional will have some value?  This would make the code "clean" 
> and still be safe.
> 
> This concept of Auto Unwrapping of Optionals is similar to Implicitly 
> Unwrapped Optionals, but is only applied when the compiler knows it is safe 
> to do so.
> 
> Take the following example:
> 
> class Test {
>var today: NSDate? = nil
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as an optional
>let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow  // 
> Requires ! or (if let) to unwrap
>// ... do stuff with timeInterval ...
>}
> }
> 
> With the above example, the compiler could known that today has a value after 
> it's set in the test method.  So why couldn't the compiler auto unwrap it 
> when accessed?  This would mean manual unwrapping would be unnecessary:
> 
> class Test {
>var today: NSDate? = nil
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as a value (not an 
> optional)
>let timeInterval: NSTimeInterval = today.timeIntervalSinceNow  // No ! 
> required (auto unwrapped)
>// ... do stuff with timeInterval ...
>}
> }
> 
> If the value later gets set to an optional value, then it will no longer be 
> auto unwrapable :
> 
> class Test {
>var today: NSDate? = nil
> 
>func optionalDay() -> NSDate? {
>return NSDate()
>}
> 
>func test() {
>today = today ?? NSDate()
>print("Today is \(today)")   // Would be printed as a value (not an 
> optional)
>let timeInterval: NSTimeInterval = today.timeIntervalSinceNow// No 
> ! required (auto unwrapped)
>let timeInterval2: NSTimeInterval = today!.timeIntervalSinceNow  // 
> Explicit unwrapping would still be allowed
> 
>// If today is assigned an optional value, we can no longer auto 
> unwrap it
>today = optionalDay()
>print("Today is \(today)")   // Would be printed as an optional
>let timeInterval3: NSTimeInterval = today!.timeIntervalSinceNow  // 
> manual unwrapping would be required
>}
> }
> 
> Note in the above example, explicit unwrapping would still be allow.  The 
> variable is still an optional.  This allows for existing code to remain 
> unchanged.
> 
> This change would encourage less use of forced unwrapping "!", generally 
> require the developer to write less code, and would maintain code safety.  On 
> the down side, it is performing some compiler “magic”.  It would be yet 
> another thing to explain when trying to introduce people to swift and 
> especially optionals.
> 
> What do you all think, would something like this be worth pursuing, what 
> other pluses or minus would this introduce, has something like this already 
> been discussed?
> 
> Thanks,
> Tod Cunningham
> 
> ___
> 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] Eliminate inconsistencies among primary collection types

2016-04-29 Thread Wolfgang H. via swift-evolution

A. When trying to declare nested collection types an inconsistency
   is unveiled:


A.1. “Array” as outer type allows for every collection type as inner
 type (“Int” used as a placeholder for “some other type”):

let test_aa: Array = []
// ok

let test_as: Array = []
// ok

let test_ad: Array> = []
// ok


A.2. “Set” as outer type allows for “Set” as inner type only:

let test_sa: Set = []
// compile time error “Type 'Array' does not conform to 
// protocol 'Hashable'”

let test_ss: Set = []
// ok

let test_sd: Set> = []
// compile time error “Type 'Dictionary' does not 
// conform to protocol 'Hashable'”


A.3. The same is true for “Dictionary” as outer type:

let test_da: Dictionary = [:]
// compile time error “Type 'Array' does not conform to 
// protocol 'Hashable'”

let test_ds: Dictionary = [:]
// ok

let test_dd: Dictionary, Int> = [:]
// compile time error “Type 'Dictionary' does not 
// conform to protocol 'Hashable'”


B. When letting Swift infer the type of collections of “Array” from
   literals another inconsistency comes to light:


B.1. “Array” as outer type behaves IMHO perfectly:

var testArray = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
print(testArray.dynamicType)
// prints “Array”
testArray.append( [ 1, "five", 25, 625 ] );
// compile time error “Cannot convert value of 'String' to
// expected element type 'Int'”; type safe


B.2. “Set” as outer type works but there is no type safety:

var testSet: Set = [ [ 1, 2, 4, 8 ], [ 1, 3, 9, 27 ] ]
print(testSet.dynamicType)
// prints “Set”
testSet.insert( [ 1, "five", 25, 625 ] )
// neither run time nor compile time errors; no type safety


B.3. The same goes for “Dictionary” as outer type:

var testDictionary = [
[ 1, 2, 4, 8 ]: "Powers of Two",
[ 1, 3, 9, 27 ]: "Powers of Three",
]
print(testDictionary.dynamicType)
// prints "Dictionary"
testDictionary[ [ 1, "five", 25, 625 ] ] = "Powers of Five"
// neither run time nor compile time errors; no type safety



— — - Wolfgang H.


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


Re: [swift-evolution] Protocol non-conformance clause

2016-04-29 Thread Xiaodi Wu via swift-evolution
Yes, certainly this works today. The motivation for Erica's question is
that this would not work without modifying the third-party code if keywords
were required to indicate implementation of protocol requirements.

One possible solution might emerge if it is possible to extend a protocol
conditional on Self not being some concrete type. Thus, asking whether
there is a way to express that.
On Fri, Apr 29, 2016 at 12:45 Thorsten Seitz  wrote:

> No problem, that still works, because the most specific implementation is
> chosen:
>
> protocol A { func foo()}
> protocol B {} // empty protocol
>
> extension A  {
> func foo() {
> print("Self is A")
> }
> }
>
> extension A where Self: B {
> func foo() {
> print("Self is B")
> }
> }
>
> // Works
> struct S1: A, B {}
> S1().foo() // Self is B
>
> struct S2: A {}
> S2().foo() // Self is A
>
>
> // Wu's example works, too
>
> struct ThirdParty {
> func foo() {
> print("Self is ThirdParty")
> }
> }
>
> extension ThirdParty : A {}
>
> ThirdParty().foo() // Self is ThirdParty
>
>
> // dynamic dispatch works, too
>
> let a1: A = S1()
> a1.foo() // Self is B
>
> let a2: A = S2()
> a2.foo() // Self is A
>
> let a3: A = ThirdParty() // Self is ThirdParty
> a3.foo()
>
>
> -Thorsten
>
>
> Am 29.04.2016 um 17:20 schrieb Erica Sadun :
>
> In Wux's example, he has third party code:
>
> ```
> Type ThirdParty {
> func foo() { print("from third party") }
> }
> ```
>
> Then in his own code, he defines protocol A and extends it:
>
> extension A {
> func foo() {
> print("Self is B")
> }
> }
>
> and conforms ThirdParty to A. But he wants the original  foo()
> implementation. Your approach
> for writing an extension for plain A without a where clause doesn't offer
> that solution. The goal
> here is "Add this default behavior *only* where a type does not conform to
> B"
>
> -- E
>
>
> On Apr 29, 2016, at 9:10 AM, Thorsten Seitz  wrote:
>
> Just writing an extension for plain A without a where clause works.
>
> -Thorsten
>
> Am 29.04.2016 um 16:03 schrieb Erica Sadun via swift-evolution <
> swift-evolution@swift.org>:
>
> Gmane is down as far as my browser is concerned and I haven't found
> anything by Googling.
>
> Given the following:
>
> protocol A {func foo()}
> protocol B {} // empty protocol
>
> extension A where Self:B {
> func foo() {
> print("Self is B")
> }
> }
>
> // Works
> struct S1: A, B {}
> S1().foo()
>
> Is there a way to produce a similar extension that exempts any type that
> conforms to B?
>
> cc'ing in Wux because this is a direct response to a scenario he brought
> up yesterday.
>
> -- E
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Protocol non-conformance clause

2016-04-29 Thread Thorsten Seitz via swift-evolution
No problem, that still works, because the most specific implementation is 
chosen:

protocol A { func foo()}
protocol B {} // empty protocol

extension A  {
func foo() {
print("Self is A")
}
}

extension A where Self: B {
func foo() {
print("Self is B")
}
}

// Works
struct S1: A, B {}
S1().foo() // Self is B

struct S2: A {}
S2().foo() // Self is A


// Wu's example works, too

struct ThirdParty {
func foo() {
print("Self is ThirdParty")
}
}

extension ThirdParty : A {}

ThirdParty().foo() // Self is ThirdParty


// dynamic dispatch works, too

let a1: A = S1()
a1.foo() // Self is B

let a2: A = S2()
a2.foo() // Self is A

let a3: A = ThirdParty() // Self is ThirdParty
a3.foo()


-Thorsten


> Am 29.04.2016 um 17:20 schrieb Erica Sadun :
> 
> In Wux's example, he has third party code:
> 
> ```
> Type ThirdParty {
> func foo() { print("from third party") }
> }
> ```
> 
> Then in his own code, he defines protocol A and extends it:
> 
> extension A {
> func foo() {
> print("Self is B")
> }
> }
> 
> and conforms ThirdParty to A. But he wants the original  foo() 
> implementation. Your approach
> for writing an extension for plain A without a where clause doesn't offer 
> that solution. The goal
> here is "Add this default behavior *only* where a type does not conform to B"
> 
> -- E
> 
> 
>> On Apr 29, 2016, at 9:10 AM, Thorsten Seitz > > wrote:
>> 
>> Just writing an extension for plain A without a where clause works.
>> 
>> -Thorsten 
>> 
>> Am 29.04.2016 um 16:03 schrieb Erica Sadun via swift-evolution 
>> >:
>> 
>>> Gmane is down as far as my browser is concerned and I haven't found 
>>> anything by Googling.
>>> 
>>> Given the following:
>>> 
>>> protocol A {func foo()}
>>> protocol B {} // empty protocol
>>> 
>>> extension A where Self:B {
>>> func foo() {
>>> print("Self is B")
>>> }
>>> }
>>> 
>>> // Works
>>> struct S1: A, B {}
>>> S1().foo()
>>> 
>>> Is there a way to produce a similar extension that exempts any type that 
>>> conforms to B?
>>> 
>>> cc'ing in Wux because this is a direct response to a scenario he brought up 
>>> yesterday.
>>> 
>>> -- E
>>> 
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-evolution 
>>> 
> 

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


Re: [swift-evolution] Disallow arbitrary expressions in selectors

2016-04-29 Thread David Rönnqvist via swift-evolution

I noticed in our code that we had one occurrence of 

#selector(SomeClass().someFunction)

which to my eyes looked like a bug. 
Disallowing arbitrary expressions looks very reasonable to me and would help 
catch small mistakes like this one. 

> 29 apr. 2016 kl. 16:40 skrev Thorsten Seitz via swift-evolution 
> :
> 
> Looks good to me!
> 
> -Thorsten 
> 
>> Am 28.04.2016 um 16:56 schrieb Alex Hoppen via swift-evolution 
>> :
>> 
>> During the implementation of SE-0064 (Referencing Objective-C selector of 
>> property getters and setters) I have come across an issue that could be 
>> resolved my a minor change to the language and simplify the compiler a lot. 
>> I have drafted a proposal below.
>> 
>> Thoughts, comments, especially objections, appreciated.
>> 
>> – Alex
>> 
>> GitHub-Link: 
>> https://github.com/ahoppen/swift-evolution/blob/arbitrary-expressions-in-selectors/proposals/-arbitrary-expressions-in-selectors.md
>> 
>> Disallow arbitrary expressions in selectors
>> Proposal: SE-
>> Author(s): Alex Hoppen
>> Status: Draft
>> Review manager: TBD
>> Introduction
>> It is currently possible to write arbitrary expressions inside #selector 
>> like the following: #selector(callThisFunc().bar). This complicates the 
>> implementation of proposals SE-0064 (Referencing Objective-C selector of 
>> property getters and setters) and SE-0062 (Referencing Objective-C 
>> key-paths) a lot. 
>> 
>> This proposal restricts expressions inside selectors to be a sequence of 
>> property or method refernces. I believe this will not be a major 
>> restrictions since arbitrary expressions in selectors are probably rarely 
>> used, have some rough edges and removing them would simplify the compiler.
>> 
>> Proposed solution
>> I propose allowed expressions inside #selector (and once implemented 
>> #keyPath) to be a series of instance or class members separated by . and 
>> allow disambiguating the last component using as.
>> 
>> Detailed design
>> Examples
>> 
>> class Address: NSObject {
>>   dynamic var street: String
>>   dynamic var town: String
>> 
>>   init(street: String, town: String) {
>> self.street = street
>> self.town = town
>>   }
>> }
>> 
>> class Person: NSObject {
>>   dynamic var name: String
>>   dynamic var homeAddress: Address
>> 
>>   func workAddress() -> Address {
>> // ...
>>   }
>> 
>>   func workAddress(formatter: AddressFormatter) -> String {
>> // ...
>>   }
>> 
>>   init(name: String, homeAddress: Address) {
>> self.name = name
>> self.homeAddress = homeAddress
>>   }
>> }
>> 
>> let me: Person = ...
>> The following examples will continue to work:
>> 
>> let _ = #selector(getter: Person.name)
>> let _ = #selector(getter: me.name)
>> 
>> let _ = #selector(getter: Person.homeAddress.street)
>> // Could also be written as
>> let _ = #selector(getter: Address.street)
>> 
>> let _ = #selector(Person.workAddress as () -> Address)
>> let _ = #selector(Person.workAddress(formatter: ))
>> I propose removing this kind of selector:
>> 
>> // Should produce selector "street". Note that the method workAddress() is 
>> never 
>> // called and its return type only used during type checking
>> let _ = #selector(getter: me.workAddress().street) 
>> 
>> // The above can be rewritten in a cleaner way like the following
>> let _ = #selector(getter: Address.street)
>> The proposed way to rewrite the selector elimininates potential confusion 
>> about the fact that calling a method inside #selector actually doesn't 
>> invoke it.
>> 
>> Grammar
>> 
>> selector → #selector(selector-modiferopt selector-path)
>> 
>> selector-modifier → getter:
>> selector-modifier → setter:
>> 
>> selector-path → type-identifier . selector-member-path as-disambiguationopt
>> selector-path → selector-member-path as-disambiguationopt
>> 
>> selector-member-path → identifier
>> selector-member-path → unqualified-name
>> selector-member-path → identifier . selector-member-path
>> 
>> as-disambiguation → as type-identifier
>> For a further rationale on why arbitrary expressions are no longer possible, 
>> see the discussion on bugs.swift.org.
>> 
>> Impact on existing code
>> Code that currently uses this feature needs to be rewritten as described in 
>> the example above. I believe, however, that the feature is rarely used so it 
>> will affect only very little source code and where it is currently used the 
>> proposed update is actually more readable.
>> 
>> Alternatives considered
>> The only alternative I see is trying to keep the current semantics and 
>> implement them for the getter:/setter: selectors.
>> 
>> 
>> ___
>> 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] multi-line string literals.

2016-04-29 Thread Cole Campbell via swift-evolution

> On Apr 29, 2016, at 9:20 AM, Erica Sadun via swift-evolution 
>  wrote:
> 
> 
>>> On Apr 28, 2016, at 4:52 PM, Brent Royal-Gordon via swift-evolution 
>>>  wrote:
>>> 
>>> Did you ever really use multiline string literals before?
>> 
>> Yes. I used Perl in the CGI script era. Believe me, I have used every 
>> quoting syntax it supports extensively, including `'` strings, `"` strings, 
>> `q` strings, `qq` strings, and heredocs. This proposal is educated by 
>> knowledge of their foibles.
>> 
>> As outlined in the "Future directions for string literals in general" 
>> section, I believe alternate delimiters (so you can embed quotes) are a 
>> separate feature and should be handled in a separate proposal. Once both 
>> features are available, they can be combined. For instance, using the 
>> `_"foo"_` syntax I sketch there for alternate delimiters, you could say:
>> 
>>let xml = _"
>>"
>>" 
>>" \(author)
>>" 
>>""_
> 
> Other than the underscores (I'm not sold on them but I could live with them), 
> this is my favorite approach:
> 
> * It supports indented left-hand alignment, which is an important to me for 
> readability
> * It avoids painful `\n"+` RHS constructions
> * It's easy to scan and understand
> * It's simple and harmonious
> 
This would ultimately be my favorite approach. I do like the underscores, 
because they're unobtrusive and don't distract the eye, but I'm interested to 
see alternative suggestions. However, I understand this is not considered in 
scope for the current proposal. Is the intention to propose alternate 
delimiters for Swift 3 now or wait?
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More lenient subscript methods over Collections (was: [Proposal] Safer half-open range operator)

2016-04-29 Thread Vladimir.S via swift-evolution

From my point of view,
truncate -> bounded
lenient -> keep "lenient:" ? "requested:" ? "optional:"?

On 29.04.2016 17:46, Thorsten Seitz wrote:

Some alternatives to 'safe:'

existing:
bounded:
valid:

-Thorsten

Am 29.04.2016 um 00:20 schrieb Luis Henrique B. Sousa via swift-evolution
>:


Thanks Vladimir, your considerations and suggestions are totally valid,
I'm going to change the document accordingly.
Also as a non-native English speaker I think that other words could fit
better, such as 'tolerant' or 'permissive' -- but I dunno if they would
look great as a label. We will come up with the right keyword for it.

In relation to bad code, it could be a valid argument if my initial
proposal was under discussion instead, where the default 'fail fast'
behaviour would be "camouflaged" and bugs would be more difficult to
catch. In this new proposal we have such features explicitly defined,
where the user will be familiar with what it does and what results to
expect for. I don't see a way that it could drive to bad written code.

- Luis

On Thu, Apr 28, 2016 at 2:37 PM, Vladimir.S > wrote:

I support this proposal. Probably we all should select the best
labels (truncate/lenient or other). As not native English speaker, I
don't feel like 'lenient' is well-known word or often-used word in
software development. But all this just a details we need to discuss.

What I think could be improved - is a motivation section. IMO the
main purpose of proposed features is not to "eliminate the need for
validations, reduce the number of fatal errors in runtime" but to
allow us to have more clean code when *such validations just don't
required*, when we just *don't care* about details.
I.e. in situations, when we'll use [max(-1, a.startIndex) ..< min(5,
a.endIndex)] and bounds checking manually to have the same result as
in proposed subscripts.

I.e. it is just a very handy addition to standard methods for
collections, just like we can get first element by index but we have
handy property '.first' for this purpose. Btw, it does not raise
error, but returns T?. I think you can add notes regarding analogues
with .first / .last properties(and probably with other) in proposal text.

Someone can argue, that by using these subscripts, coders can write
'bad' code - but I can't accept such an argument - 'bad' coders
already can write 'bad' code with other features of Swift and at the
end they can implement these subscripts in their project and write
'bad' code. Should we stop to introduce handy and explicit feature
for 'good' coders because of this?

On 28.04.2016 15:11, Luis Henrique B. Sousa via swift-evolution wrote:

As we have discussed throughout this thread, the initial proposal was
modified to include alternative subscript methods instead of
modifying the
default operator/subscript behaviour.
The first draft is
here:

https://github.com/luish/swift-evolution/blob/more-lenient-subscripts/proposals/-more-lenient-collections-subscripts.md

I've also put this as a gist so that you can leave comments with
respect to
the proposal document itself. Any suggestion or help is very welcome.
https://gist.github.com/luish/832c34ee913159f130d97a914810dbd8

Regards,

- Luis

On Mon, Apr 11, 2016 at 1:23 PM, Luis Henrique B. Sousa

>> wrote:

This proposal seeks to provide a safer ..< (aka half-open range
operator) in order to avoid **Array index out of range**
errors in
execution time.

Here is my first draft for this proposal:


https://github.com/luish/swift-evolution/blob/half-open-range-operator/proposals/-safer-half-open-range-operator.md

In short, doing that in Swift causes a runtime error:

leta =[1,2,3]
letb =a[0..<5]
print(b)

> Error running code:
> fatal error: Array index out of range

The proposed solution is to slice the array returning all
elements that
are below the half-open operator, even though the number of
elements is
lesser than the ending of the half-open operator. So the
example above
would return [1,2,3].
We can see this very behaviour in other languages, such as
Python and
Ruby as shown in the proposal draft.

This would eliminate the need for verifications on the array size
before slicing it -- and consequently runtime errors in cases
when the
programmer didn't.

Viewing that it is my very 

Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 29, 2016 at 4:02 AM, David Hart  wrote:
> But Collection has to have an extension which explicitly mentions
> IndexingIterator:
>
> extension Collection where Iterator == IndexingIterator {
> /// Returns an iterator over the elements of the collection.
> public func makeIterator() -> IndexingIterator {
> return IndexingIterator(_elements: self)
> }
> }
>
> And Array, for example, has to be explicit:
>
> public typealias Iterator = IndexingIterator<${Self}>

This might be a workaround for a compiler bug (that it couldn't infer the type).

> So I still don’t see how defining:
>
> associatedtype Iterator : IteratorProtocol = IndexingIterator
>
> has created any default behaviour.
>
> When you say "The fact that the compiler does not allow to use the inferred
> ‘Foo' type actually looks like a bug to me.”, could you give me an example
> of how you would have imagined this default behaviour to work in the case of
> Array? Would have expected Array not to have to define its typealias?

Right, I would expect Array to not need to mention Iterator at all in
its definition.

Take a look at stdlib/public/core/CollectionOfOne.swift.  It does not
define SubSequence or Indices.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Moving where Clauses Out Of Parameter Lists

2016-04-29 Thread Erica Sadun via swift-evolution
This is one of those where I keep hoping someone will pick it up and get the 
proposal out there.

-- E

> On Apr 29, 2016, at 8:57 AM, David Hart via swift-evolution 
>  wrote:
> 
> What’s up with this great idea? Can’t see a proposal on swift-evolution 
> anywhere.
> 
>> On 08 Apr 2016, at 08:15, Chris Lattner via swift-evolution 
>>  wrote:
>> 
>> 
>>> On Apr 6, 2016, at 11:30 AM, Developer via swift-evolution 
>>>  wrote:
>>> 
>>> If you've ever gotten to the point where you have a sufficiently generic 
>>> interface to a thing and you need to constrain it, possibly in an 
>>> extension, maybe for a generic free function or operator, you know what a 
>>> pain the syntax can be for these kinds of operations.  For example, the 
>>> Swift book implements this example to motivate where clauses
>>> 
>>> func anyCommonElements >> T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> 
>>> (lhs: T, _ rhs: U) -> Bool
>>> 
>>> This is noisy and uncomfortable to my eyes, and almost impossible to align 
>>> correctly.  Per a short discussion on Twitter with Joe Groff and Erica 
>>> Sadun, I'd like so see what the community feels about moving the where 
>>> clause out of the angle brackets.  So that example becomes
>>> 
>>> func anyCommonElements 
>>> where T.Generator.Element: Equatable, T.Generator.Element == 
>>> U.Generator.Element
>>> (lhs: T, _ rhs: U) -> Bool
>>> 
>>> Or, if you're feeling ambitious, even
>>> 
>>> func anyCommonElements 
>>> where T : SequenceType, U : SequenceType,
>>> T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element
>>> (lhs: T, _ rhs: U) -> Bool
>>> 
>>> Thoughts?
>> 
>> +1, long overdue.  Please keep basic constraints (ones expressible without a 
>> ‘where’ clause, like simple conformances) inline though.
>> 
>> -Chris
>> ___
>> swift-evolution mailing list
>> swift-evolution@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [Proposal] More lenient subscript methods over Collections (was: [Proposal] Safer half-open range operator)

2016-04-29 Thread Thorsten Seitz via swift-evolution
Some alternatives to 'safe:'

existing:
bounded:
valid:

-Thorsten 

> Am 29.04.2016 um 00:20 schrieb Luis Henrique B. Sousa via swift-evolution 
> :
> 
> Thanks Vladimir, your considerations and suggestions are totally valid, I'm 
> going to change the document accordingly. 
> Also as a non-native English speaker I think that other words could fit 
> better, such as 'tolerant' or 'permissive' -- but I dunno if they would look 
> great as a label. We will come up with the right keyword for it.
> 
> In relation to bad code, it could be a valid argument if my initial proposal 
> was under discussion instead, where the default 'fail fast' behaviour would 
> be "camouflaged" and bugs would be more difficult to catch. In this new 
> proposal we have such features explicitly defined, where the user will be 
> familiar with what it does and what results to expect for. I don't see a way 
> that it could drive to bad written code.
> 
> - Luis
> 
>> On Thu, Apr 28, 2016 at 2:37 PM, Vladimir.S  wrote:
>> I support this proposal. Probably we all should select the best labels 
>> (truncate/lenient or other). As not native English speaker, I don't feel 
>> like 'lenient' is well-known word or often-used word in software 
>> development. But all this just a details we need to discuss.
>> 
>> What I think could be improved - is a motivation section. IMO the main 
>> purpose of proposed features is not to "eliminate the need for validations, 
>> reduce the number of fatal errors in runtime" but to allow us to have more 
>> clean code when *such validations just don't required*, when we just *don't 
>> care* about details.
>> I.e. in situations, when we'll use [max(-1, a.startIndex) ..< min(5, 
>> a.endIndex)] and bounds checking manually to have the same result as in 
>> proposed subscripts.
>> 
>> I.e. it is just a very handy addition to standard methods for collections, 
>> just like we can get first element by index but we have handy property 
>> '.first' for this purpose. Btw, it does not raise error, but returns T?. I 
>> think you can add notes regarding analogues with .first / .last 
>> properties(and probably with other) in proposal text.
>> 
>> Someone can argue, that by using these subscripts, coders can write 'bad' 
>> code - but I can't accept such an argument - 'bad' coders already can write 
>> 'bad' code with other features of Swift and at the end they can implement 
>> these subscripts in their project and write 'bad' code. Should we stop to 
>> introduce handy and explicit feature for 'good' coders because of this?
>> 
>>> On 28.04.2016 15:11, Luis Henrique B. Sousa via swift-evolution wrote:
>>> As we have discussed throughout this thread, the initial proposal was
>>> modified to include alternative subscript methods instead of modifying the
>>> default operator/subscript behaviour.
>>> The first draft is
>>> here: 
>>> https://github.com/luish/swift-evolution/blob/more-lenient-subscripts/proposals/-more-lenient-collections-subscripts.md
>>> 
>>> I've also put this as a gist so that you can leave comments with respect to
>>> the proposal document itself. Any suggestion or help is very welcome.
>>> https://gist.github.com/luish/832c34ee913159f130d97a914810dbd8
>>> 
>>> Regards,
>>> 
>>> - Luis
>>> 
>>> On Mon, Apr 11, 2016 at 1:23 PM, Luis Henrique B. Sousa >> > wrote:
>>> 
>>> This proposal seeks to provide a safer ..< (aka half-open range
>>> operator) in order to avoid **Array index out of range** errors in
>>> execution time.
>>> 
>>> Here is my first draft for this proposal:
>>> 
>>> https://github.com/luish/swift-evolution/blob/half-open-range-operator/proposals/-safer-half-open-range-operator.md
>>> 
>>> In short, doing that in Swift causes a runtime error:
>>> 
>>> leta =[1,2,3]
>>> letb =a[0..<5]
>>> print(b)
>>> 
>>> > Error running code:
>>> > fatal error: Array index out of range
>>> 
>>> The proposed solution is to slice the array returning all elements that
>>> are below the half-open operator, even though the number of elements is
>>> lesser than the ending of the half-open operator. So the example above
>>> would return [1,2,3].
>>> We can see this very behaviour in other languages, such as Python and
>>> Ruby as shown in the proposal draft.
>>> 
>>> This would eliminate the need for verifications on the array size
>>> before slicing it -- and consequently runtime errors in cases when the
>>> programmer didn't.
>>> 
>>> Viewing that it is my very first proposal, any feedback will be helpful.
>>> 
>>> Thanks!
>>> 
>>> Luis Henrique Borges
>>> @luishborges
>>> 
>>> 
>>> 
>>> 
>>> ___
>>> swift-evolution mailing list
>>> swift-evolution@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>> 
> 
> 

Re: [swift-evolution] Protocol non-conformance clause

2016-04-29 Thread Thorsten Seitz via swift-evolution
Just writing an extension for plain A without a where clause works.

-Thorsten 

> Am 29.04.2016 um 16:03 schrieb Erica Sadun via swift-evolution 
> :
> 
> Gmane is down as far as my browser is concerned and I haven't found anything 
> by Googling.
> 
> Given the following:
> 
> protocol A {func foo()}
> protocol B {} // empty protocol
> 
> extension A where Self:B {
> func foo() {
> print("Self is B")
> }
> }
> 
> // Works
> struct S1: A, B {}
> S1().foo()
> 
> Is there a way to produce a similar extension that exempts any type that 
> conforms to B?
> 
> cc'ing in Wux because this is a direct response to a scenario he brought up 
> yesterday.
> 
> -- E
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Moving where Clauses Out Of Parameter Lists

2016-04-29 Thread David Hart via swift-evolution
What’s up with this great idea? Can’t see a proposal on swift-evolution 
anywhere.

> On 08 Apr 2016, at 08:15, Chris Lattner via swift-evolution 
>  wrote:
> 
> 
>> On Apr 6, 2016, at 11:30 AM, Developer via swift-evolution 
>>  wrote:
>> 
>> If you've ever gotten to the point where you have a sufficiently generic 
>> interface to a thing and you need to constrain it, possibly in an extension, 
>> maybe for a generic free function or operator, you know what a pain the 
>> syntax can be for these kinds of operations.  For example, the Swift book 
>> implements this example to motivate where clauses
>> 
>> func anyCommonElements > T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> 
>> (lhs: T, _ rhs: U) -> Bool
>> 
>> This is noisy and uncomfortable to my eyes, and almost impossible to align 
>> correctly.  Per a short discussion on Twitter with Joe Groff and Erica 
>> Sadun, I'd like so see what the community feels about moving the where 
>> clause out of the angle brackets.  So that example becomes
>> 
>> func anyCommonElements 
>> where T.Generator.Element: Equatable, T.Generator.Element == 
>> U.Generator.Element
>> (lhs: T, _ rhs: U) -> Bool
>> 
>> Or, if you're feeling ambitious, even
>> 
>> func anyCommonElements 
>> where T : SequenceType, U : SequenceType,
>> T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element
>> (lhs: T, _ rhs: U) -> Bool
>> 
>> Thoughts?
> 
> +1, long overdue.  Please keep basic constraints (ones expressible without a 
> ‘where’ clause, like simple conformances) inline though.
> 
> -Chris
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


Re: [swift-evolution] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread David Rönnqvist via swift-evolution

>   * What is your evaluation of the proposal?

+1 This is a useful addition.

As other have already pointed out, I also feel that `scan` is the least 
intuitive name among these and that the `reduce`/`reductions` pairing would do 
a good job at explaining the relation between the two.

If I’ve understood the evolution process correctly, the broader naming of 
existing prefix, suffix, split, dropFirst, dropLast, etc. functions is not in 
scope of this proposal. Given that, I feel that the main goal regarding naming 
the proposed functions is to fit in well with the existing name. I feel that 
there is a small “term of art” argument to be made for takeWhile/dropWhile, but 
also that prefix(while:)/drop(while:) is a closer match to Swifts naming of 
similar existing functions. I don’t have strong preferences for either of these 
naming and would be absolutely fine with either.

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

Yes, these are good building blocks for other functionality and are useful 
additions to the standard library 

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

Yes, in both naming and functionality it fits well with existing functions for 
operating on sequences and collections 

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

I wonder if something like Haskell’s [`span`][1] (returning a tuple of 
`prefix(while:)` and `drop(while:)` would be a good addition alongside these. 
It also doesn’t have a very intuitive name, so in that case we would have to 
come up with something better. 

[1]: http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:span 

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

Read of the proposal, read the evolution proposal thread, and a small study of 
similar features in other languages.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Disallow arbitrary expressions in selectors

2016-04-29 Thread Thorsten Seitz via swift-evolution
Looks good to me!

-Thorsten 

> Am 28.04.2016 um 16:56 schrieb Alex Hoppen via swift-evolution 
> :
> 
> During the implementation of SE-0064 (Referencing Objective-C selector of 
> property getters and setters) I have come across an issue that could be 
> resolved my a minor change to the language and simplify the compiler a lot. I 
> have drafted a proposal below.
> 
> Thoughts, comments, especially objections, appreciated.
> 
> – Alex
> 
> GitHub-Link: 
> https://github.com/ahoppen/swift-evolution/blob/arbitrary-expressions-in-selectors/proposals/-arbitrary-expressions-in-selectors.md
> 
> Disallow arbitrary expressions in selectors
> Proposal: SE-
> Author(s): Alex Hoppen
> Status: Draft
> Review manager: TBD
> Introduction
> 
> It is currently possible to write arbitrary expressions inside #selector like 
> the following: #selector(callThisFunc().bar). This complicates the 
> implementation of proposals SE-0064 (Referencing Objective-C selector of 
> property getters and setters) and SE-0062 (Referencing Objective-C key-paths) 
> a lot. 
> 
> This proposal restricts expressions inside selectors to be a sequence of 
> property or method refernces. I believe this will not be a major restrictions 
> since arbitrary expressions in selectors are probably rarely used, have some 
> rough edges and removing them would simplify the compiler.
> 
> Proposed solution
> 
> I propose allowed expressions inside #selector (and once implemented 
> #keyPath) to be a series of instance or class members separated by . and 
> allow disambiguating the last component using as.
> 
> Detailed design
> 
> Examples
> 
> class Address: NSObject {
>   dynamic var street: String
>   dynamic var town: String
> 
>   init(street: String, town: String) {
> self.street = street
> self.town = town
>   }
> }
> 
> class Person: NSObject {
>   dynamic var name: String
>   dynamic var homeAddress: Address
> 
>   func workAddress() -> Address {
> // ...
>   }
> 
>   func workAddress(formatter: AddressFormatter) -> String {
> // ...
>   }
> 
>   init(name: String, homeAddress: Address) {
> self.name = name
> self.homeAddress = homeAddress
>   }
> }
> 
> let me: Person = ...
> The following examples will continue to work:
> 
> let _ = #selector(getter: Person.name)
> let _ = #selector(getter: me.name)
> 
> let _ = #selector(getter: Person.homeAddress.street)
> // Could also be written as
> let _ = #selector(getter: Address.street)
> 
> let _ = #selector(Person.workAddress as () -> Address)
> let _ = #selector(Person.workAddress(formatter: ))
> I propose removing this kind of selector:
> 
> // Should produce selector "street". Note that the method workAddress() is 
> never 
> // called and its return type only used during type checking
> let _ = #selector(getter: me.workAddress().street) 
> 
> // The above can be rewritten in a cleaner way like the following
> let _ = #selector(getter: Address.street)
> The proposed way to rewrite the selector elimininates potential confusion 
> about the fact that calling a method inside #selector actually doesn't invoke 
> it.
> 
> Grammar
> 
> selector → #selector(selector-modiferopt selector-path)
> 
> selector-modifier → getter:
> selector-modifier → setter:
> 
> selector-path → type-identifier . selector-member-path as-disambiguationopt
> selector-path → selector-member-path as-disambiguationopt
> 
> selector-member-path → identifier
> selector-member-path → unqualified-name
> selector-member-path → identifier . selector-member-path
> 
> as-disambiguation → as type-identifier
> For a further rationale on why arbitrary expressions are no longer possible, 
> see the discussion on bugs.swift.org.
> 
> Impact on existing code
> 
> Code that currently uses this feature needs to be rewritten as described in 
> the example above. I believe, however, that the feature is rarely used so it 
> will affect only very little source code and where it is currently used the 
> proposed update is actually more readable.
> 
> Alternatives considered
> 
> The only alternative I see is trying to keep the current semantics and 
> implement them for the getter:/setter: selectors.
> 
> 
> ___
> 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] Moving where Clauses Out Of Parameter Lists

2016-04-29 Thread Maximilian Hünenberger via swift-evolution
+1 I almost fully agree with all your points. However I disagree with your 
first point:

What do you mean by: "I think it's more natural to restrict generic type 
parameters to the immediate local scope"

To me it feels like an "associated type" so it should be almost equally exposed 
in comparison to "associatedtype" of a protocol

Kind regards
- Maximilian

> Am 07.04.2016 um 10:44 schrieb Pyry Jahkola via swift-evolution 
> :
> 
> Jordan,
> 
> Your comments brought up a few more closely related ideas that have been 
> bubbling under.
> 
> To everyone,
> 
> Sorry for going beyond topic here. The discussion of the further proposals 
> below should be taken into their own threads if there's interest. I'm just 
> trying to motivate what else moving out the `where` clause would make 
> possible.
> 
> 1. My counter-proposal against making generic parameters public
> 
>> Another factor here is that we've been planning for a while for generic 
>> parameters to types to be exposed as implicit member typealiases, since they 
>> already conflict with the namespace for member typealiases. Therefore it's 
>> important to name generic parameters to types well, but less important to do 
>> so for generic parameters for functions. (They're also much less likely to 
>> be ad hoc for types; there has to be something that describes the relation 
>> between the Self type and the parameter, while the function might not have 
>> anything more interesting than "operand".)
> 
> I disagree with that. I think it's more natural to restrict generic type 
> parameters to the immediate local scope of the class/struct/enum definition 
> or extension, and simply allow making the type public with `typealias`. For 
> example, this would make `Element` a public member of `Array`:
> 
> public enum Result {
> public typealias Value = T // This makes `Value` public for 
> extensions and everyone
> }
> 
> I would even allow publishing the otherwise local name by repeating it in 
> `typealias` like this:
> 
> public struct Array { // This `Element` is only available in 
> (the missing) where clause and the scope below.
> public typealias Element = Element // This line makes `Element` 
> available everywhere, see below.
> }
> 
> extension Array { // <- Regardless of the pattern (`T`) used here,
> var mid: Element? { // the type `Element = T` is available here
> return ...  // because it was made public elsewhere.
> }
> }
> extension Array { // <- An example of pattern matching (see 
> further below).
> // Ditto, `Element = T?`
> }
> 
> typealias Ints = [Int]
> let x: Ints.Element = ... // Int
> 
> Next, I propose how to extend this syntax with pattern matching. The above 
> thinking is a natural progression from the use of pattern matching for 
> introducing generic type parameters in type `extension`s.
> 
> 
> 2. Proposal to enable pattern matching of generic types in generic parameters
> 
>> This is also a minor point against declaring generic parameters for 
>> extensions, since they would have to match up. We also do need a syntax some 
>> day to represent new parameters:
>> 
>> // For expository purposes only:
>> extension  Array where Element == Optional
>> 
>> But that deserves its own proposal. I just don't want us to paint ourselves 
>> into a corner.
> 
> I agree that we need that feature. But instead of your proposed syntax, I'd 
> take influence from the already existing pattern matching that we have at 
> value level, such that:
> 
> 1. any generic type expressions within the angle brackets `<...>` are taken 
> as patterns to match against  (e.g. `Array`, `Optional`, 
> `Dictionary`), and
> 2. all non-generic type identifiers in those expressions are taken as generic 
> parameters and not concrete types (`Element`, `Foo`, or `S`, respectively).
> 
> Your example would translate into the first of these two:
> 
> extension Array { // extending [T?] doesn't even need any 
> `where` clause
> func unwrapAll() -> [T] { ... }
> }
> 
> extension Dictionary> { // This pattern match 
> requires the same `K` twice.
> subscript(x: K, y: K) -> V { ... }
> }
> 
> The generic parameters would shadow any existing names in the outer scope, 
> i.e. `extension Array` would mean the same as `extension 
> Array`. But it would be a good idea to add a warning (or linter 
> error) at least when stdlib types such as `Swift.String` are shadowed like 
> that. I think the benefits from pattern matching outweigh the possible 
> confusion, especially since you can't use any members of `String` if you 
> mistakenly wrote `extension Array { ... }` instead of `extension 
> Array where T == String`.
> 
> With this syntax, we could also allow extending Array, Dictionary, and 
> Optional in their more natural notation:
> 
> extension [T?] {
> 

Re: [swift-evolution] [Pitch] Requiring proactive overrides for default protocol implementations.

2016-04-29 Thread Xiaodi Wu via swift-evolution
I'd be keenly interested in something that would improve the experience of
conforming a type to a protocol. I think others would as well. A
sufficiently sophisticated solution would:

* catch unintentional typos that cause required functions to be incorrectly
named
* show, ideally prospectively, which required functions have default
implementations
* clarify (and this is obviously a cherry-on-top scenario) what protocol
requirements any particular function helps to satisfy as well as which
combination of implementations is used to synthesize a default
implementation of another function (e.g. <= synthesized from < and ==; this
would help to determine whether it might be more efficient to roll your own
override)
* support all retroactive modeling scenarios currently supported

I tried to propose a keyword-based solution (less sophisticated than yours)
a while back, and I've been convinced that the drawbacks in terms of
decreased expressiveness in retroactive modeling might be insurmountable.
Perhaps it would be worthwhile exploring improvements in tooling and
documentation (including annotation of the code itself) in order to address
some of these areas?
On Fri, Apr 29, 2016 at 09:14 Erica Sadun via swift-evolution <
swift-evolution@swift.org> wrote:

> On Apr 28, 2016, at 10:00 PM, Jordan Rose  wrote:
>
> Hi, Erica. Sorry for not participating in the first round here. I’m…not so
> happy with this direction, for a number of reasons. (I apologize for the
> laundry list, but they’re not really related complaints.)
>
> - ‘required’ already means something today: it means “this initializer
> must be present on all subclasses”. The reason it only applies
> to initializers is because all other members are always present on all
> subclasses.
>
> (Counter-argument: using ‘required’ on an initializer could be seen as
> making an implicit protocol, just for that class hierarchy.)
>
> - ‘override’ likewise already has a meaning; allowing ‘override’ to be
> satisfied by a protocol requirement means that it might miss an
> override intended for a superclass—or inadvertently become one when an SDK
> is updated.
>
> (Counter-argument: that last can happen to protocols already.)
>
> - This doesn’t cover cases where methods in one protocol extension satisfy
> requirements in another.
>
> - This doesn’t cover retroactive modeling.
>
> - I’m not sure what it means to "prefer an overridden implementation in
> preference in reverse hierarchical order: type extensions take precedence
> over type declarations over protocol extensions over protocol declarations
> (assuming protocol declarations eventually adopt default implementations)”.
> Protocol conformance is decided at compile time; there won’t ever be any
> members in type extensions that take precedent over a type declaration
> without causing a conflict. (That is, currently you are not allowed to
> define such a member.)
>
> - A member in the type does *not* “override" a member in a protocol
> extension today, because such a call is not dynamically dispatched. Making
> protocol extension members dynamically dispatched is challenging at the
> least and would require an implementation plan in the proposal.
>
> - Thank you for writing up all of the source compatibility cases! I
> *think* there’s no issue with binary compatibility, since IIUC the
> proposal doesn’t change how anything is implemented, and we think we know
> how to handle binary compatibility there. But I’d like to think about it
> a little more.
>
> - The “A.foo(self)()” syntax is clever, but it doesn’t work correctly for
> mutating methods (because you can’t curry an inout). On the other hand,
> JoeG already brought up the idea of making ‘self’ the first argument of the
> implicit static member. It still doesn’t solve the problem of *picking* a
> protocol extension, but that’s not new. (This isn’t a complaint, I guess,
> just a note.)
>
>
> I’m not sure I have a meaningful summary or conclusion, but I’d be
> hesitant to do all of this without these concerns being addressed.
>
> Jordan
>
>
> I've arrived at the "just table it and find something more productive to
> work on" stage.  This pitch grew out of my conviction that doing "near
> miss" detection was the wrong approach for supporting and documenting
> developer intent decisions. If there's no strong support my the core
> concept (enhancing safety by introducing semantic compiler hints) then all
> the implementation details in the world don't get me anywhere.
>
> Without developing a quorum that supports the underlying philosophy,
> regardless of implementation, I'm not going to push this any further. The
> gist is updated but I have no plans to further mold it into a proposal.
>
> -- E
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
___
swift-evolution mailing list

[swift-evolution] Auto Unwrapping Of Optionals

2016-04-29 Thread Tod Cunningham via swift-evolution
I'm new to the swift evolution community, but I wanted to toss an idea out 
there to get some feedback on it. So here it goes...

Currently, if you assign a non-nil value to an optional and then want to access 
that optional later, in the same context, you need to manually unwrap the 
value.  This is usually done either by using "!" or by using something like "if 
let" or guard.

What would it be like if the compiler could auto unwrap, in cases where in 
knows the optional will have some value?  This would make the code "clean" and 
still be safe.

This concept of Auto Unwrapping of Optionals is similar to Implicitly Unwrapped 
Optionals, but is only applied when the compiler knows it is safe to do so.

Take the following example:

class Test {
var today: NSDate? = nil
func test() {
today = today ?? NSDate()
print("Today is \(today)")   // Would be printed as an optional
let timeInterval: NSTimeInterval = today!.timeIntervalSinceNow  // 
Requires ! or (if let) to unwrap
// ... do stuff with timeInterval ...
}
}

With the above example, the compiler could known that today has a value after 
it's set in the test method.  So why couldn't the compiler auto unwrap it when 
accessed?  This would mean manual unwrapping would be unnecessary:

class Test {
var today: NSDate? = nil
func test() {
today = today ?? NSDate()
print("Today is \(today)")   // Would be printed as a value (not an 
optional)
let timeInterval: NSTimeInterval = today.timeIntervalSinceNow  // No ! 
required (auto unwrapped)
// ... do stuff with timeInterval ...
}
}

If the value later gets set to an optional value, then it will no longer be 
auto unwrapable :

class Test {
var today: NSDate? = nil

func optionalDay() -> NSDate? {
return NSDate()
}

func test() {
today = today ?? NSDate()
print("Today is \(today)")   // Would be printed as a value (not an 
optional)
let timeInterval: NSTimeInterval = today.timeIntervalSinceNow// No 
! required (auto unwrapped)
let timeInterval2: NSTimeInterval = today!.timeIntervalSinceNow  // 
Explicit unwrapping would still be allowed

// If today is assigned an optional value, we can no longer auto unwrap 
it
today = optionalDay()
print("Today is \(today)")   // Would be printed as an optional
let timeInterval3: NSTimeInterval = today!.timeIntervalSinceNow  // 
manual unwrapping would be required
}
}

Note in the above example, explicit unwrapping would still be allow.  The 
variable is still an optional.  This allows for existing code to remain 
unchanged.

This change would encourage less use of forced unwrapping "!", generally 
require the developer to write less code, and would maintain code safety.  On 
the down side, it is performing some compiler “magic”.  It would be yet another 
thing to explain when trying to introduce people to swift and especially 
optionals.

What do you all think, would something like this be worth pursuing, what other 
pluses or minus would this introduce, has something like this already been 
discussed?

Thanks,
Tod Cunningham

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


Re: [swift-evolution] multi-line string literals.

2016-04-29 Thread Erica Sadun via swift-evolution

> On Apr 28, 2016, at 4:52 PM, Brent Royal-Gordon via swift-evolution 
>  wrote:
> 
>> Did you ever really use multiline string literals before?
> 
> Yes. I used Perl in the CGI script era. Believe me, I have used every quoting 
> syntax it supports extensively, including `'` strings, `"` strings, `q` 
> strings, `qq` strings, and heredocs. This proposal is educated by knowledge 
> of their foibles.
> 
> As outlined in the "Future directions for string literals in general" 
> section, I believe alternate delimiters (so you can embed quotes) are a 
> separate feature and should be handled in a separate proposal. Once both 
> features are available, they can be combined. For instance, using the 
> `_"foo"_` syntax I sketch there for alternate delimiters, you could say:
> 
>   let xml = _"
>   "
>   " 
>   " \(author)
>   " 
>   ""_

Other than the underscores (I'm not sold on them but I could live with them), 
this is my favorite approach:

* It supports indented left-hand alignment, which is an important to me for 
readability
* It avoids painful `\n"+` RHS constructions
* It's easy to scan and understand
* It's simple and harmonious

-- E

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


Re: [swift-evolution] [Review] SE-0032: Add find method to SequenceType

2016-04-29 Thread Erica Sadun via swift-evolution
I like the functionality. I remain concerned that Sequence types do not 
guarantee termination and the semantics are better represented by something 
along the line of "ordered collection". Related notes here: 
https://gist.github.com/erica/1fa219d79572c2916acd7de91a2f221a 


-- E


> On Apr 28, 2016, at 12:11 PM, Chris Lattner via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of "SE-0032: Add find method to SequenceType" begins now and runs 
> through May 3. The proposal is available here:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0032-sequencetype-find.md

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


Re: [swift-evolution] [Review] SE-0045: Add scan, prefix(while:), drop(while:), and iterate to the stdlib

2016-04-29 Thread Erica Sadun via swift-evolution

> On Apr 28, 2016, at 10:15 PM, Brent Royal-Gordon via swift-evolution 
>  wrote:
> I believe that `prefix(while:)` and `dropFirst(while:)` would be most 
> consistent with the current standard library, but frankly, I consider that an 
> indictment of the current names.
> `skip` is better than `drop`, but they are both pigs; one's just wearing 
> lipstick.

This is a great place to bring up "terms of art", again. When looking to other 
languages as our muse, trying to adapt syntax into Swift's tortured guidance 
system is less successful than retaining those terms, which have already been 
extensively bikeshedded in their original development. I much prefer takeWhile 
dropWhile, etc.

-- E


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


Re: [swift-evolution] [Pitch] Requiring proactive overrides for default protocol implementations.

2016-04-29 Thread Erica Sadun via swift-evolution
On Apr 28, 2016, at 10:00 PM, Jordan Rose  wrote:
> Hi, Erica. Sorry for not participating in the first round here. I’m…not so 
> happy with this direction, for a number of reasons. (I apologize for the 
> laundry list, but they’re not really related complaints.)
> 
> - ‘required’ already means something today: it means “this initializer must 
> be present on all subclasses”. The reason it only applies to initializers is 
> because all other members are always present on all subclasses.
> 
> (Counter-argument: using ‘required’ on an initializer could be seen as making 
> an implicit protocol, just for that class hierarchy.)
> 
> - ‘override’ likewise already has a meaning; allowing ‘override’ to be 
> satisfied by a protocol requirement means that it might miss an override 
> intended for a superclass—or inadvertently become one when an SDK is updated.
> 
> (Counter-argument: that last can happen to protocols already.)
> 
> - This doesn’t cover cases where methods in one protocol extension satisfy 
> requirements in another.
> 
> - This doesn’t cover retroactive modeling.
> 
> - I’m not sure what it means to "prefer an overridden implementation in 
> preference in reverse hierarchical order: type extensions take precedence 
> over type declarations over protocol extensions over protocol declarations 
> (assuming protocol declarations eventually adopt default implementations)”. 
> Protocol conformance is decided at compile time; there won’t ever be any 
> members in type extensions that take precedent over a type declaration 
> without causing a conflict. (That is, currently you are not allowed to define 
> such a member.)
> 
> - A member in the type does not “override" a member in a protocol extension 
> today, because such a call is not dynamically dispatched. Making protocol 
> extension members dynamically dispatched is challenging at the least and 
> would require an implementation plan in the proposal.
> 
> - Thank you for writing up all of the source compatibility cases! I think 
> there’s no issue with binary compatibility, since IIUC the proposal doesn’t 
> change how anything is implemented, and we think we know how to handle binary 
> compatibility there. But I’d like to think about it a little more.
> 
> - The “A.foo(self)()” syntax is clever, but it doesn’t work correctly for 
> mutating methods (because you can’t curry an inout). On the other hand, JoeG 
> already brought up the idea of making ‘self’ the first argument of the 
> implicit static member. It still doesn’t solve the problem of picking a 
> protocol extension, but that’s not new. (This isn’t a complaint, I guess, 
> just a note.)
> 
> 
> I’m not sure I have a meaningful summary or conclusion, but I’d be hesitant 
> to do all of this without these concerns being addressed.
> 
> Jordan

I've arrived at the "just table it and find something more productive to work 
on" stage.  This pitch grew out of my conviction that doing "near miss" 
detection was the wrong approach for supporting and documenting developer 
intent decisions. If there's no strong support my the core concept (enhancing 
safety by introducing semantic compiler hints) then all the implementation 
details in the world don't get me anywhere.

Without developing a quorum that supports the underlying philosophy, regardless 
of implementation, I'm not going to push this any further. The gist is updated 
but I have no plans to further mold it into a proposal.

-- E

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


[swift-evolution] Protocol non-conformance clause

2016-04-29 Thread Erica Sadun via swift-evolution
Gmane is down as far as my browser is concerned and I haven't found anything by 
Googling.

Given the following:

protocol A {func foo()}
protocol B {} // empty protocol

extension A where Self:B {
func foo() {
print("Self is B")
}
}

// Works
struct S1: A, B {}
S1().foo()

Is there a way to produce a similar extension that exempts any type that 
conforms to B?

cc'ing in Wux because this is a direct response to a scenario he brought up 
yesterday.

-- E

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


Re: [swift-evolution] Extending init checks for property initialization

2016-04-29 Thread Wallacy via swift-evolution
Why not use the Designated Initializers and Convenience Initializers

 ?

private var videoPlayer: AVPlayer
private var videoPlayerLayer: AVPlayerLayer

required override init(){ // <-- commonInitialization()
videoPlayer = AVPlayer()
videoPlayerLayer = AVPlayerLayer()
super.init()
}

convenience init?(coder decoder: NSCoder) {
self.init();
}

Em qui, 28 de abr de 2016 às 12:36, Shannon Potter via swift-evolution <
swift-evolution@swift.org> escreveu:

> Consider a relatively-common init pattern:
>
> class SomeViewController: UIViewController {
>
> // MARK: Properties
>
> private var videoPlayer: AVPlayer
> private var videoPlayerLayer: AVPlayerLayer
>
> // MARK: - Object Lifecycle
>
> override init(nibName: String?, bundle nibBundle: NSBundle?) {
> super.init(nibName: nibName, bundle: nibBundle)
>
> commonInitialization()
> }
>
> required init?(coder decoder: NSCoder) {
> super.init(coder: decoder)
>
> commonInitialization()
> }
>
> private func commonInitialization() {
> videoPlayer = AVPlayer(...)
> videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
> }
>
> }
>
> This does not work. Both properties are non-optional, and the compiler
> complains that they are not initialized in either init method. It seems
> rather common to want a single point of contact regarding object
> initialization, regardless of the path taken to initialize that object.
> Ideally, objects could all be funneled to one designated initializer, but
> this isn’t always the case.
>
> What are people’s thoughts about either a specialized function that is
> always called at the very end of each object’s lifecycle OR some sort of
> attribute for a function that hints that the compiler should follow it if
> called in an init function to check for property initialization?
>
> func commonInit() {
>
> }
>
> or
>
> @extend_init private func commonInitialization() {
>
> }
> ___
> 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] [Idea] Pin down IteratorProtocol's mutation semantics

2016-04-29 Thread Brent Royal-Gordon via swift-evolution
IteratorProtocol imposes some strange limitations and preconditions which 
basically boil down to "this protocol is fundamentally mutating, but we don't 
want to promise whether you're going to get value or reference semantics, so 
don't do anything that might behave differently depending on that, and by the 
way we can't possibly enforce that in the type system, so good luck finding any 
mistakes yourself". As far as I can tell, this is because some iterators *must* 
provide reference semantics (e.g. when reading from a socket), while others can 
be implemented perhaps more efficiently with a value type.

How bad would it be to force all iterators to provide reference semantics by 
making IteratorProtocol a class protocol? Particularly if we assume that 
iterators could generally be made `final`?

Alternatively, how valuable is it to specify that you can't use an iterator in 
a way that would expose whether it is a reference or a value type? The only 
iterators I can think of which would *need* to be reference types are ones 
which draw elements from an outside source; for those, it's unsurprising that 
copying doesn't "work". Are there cases I'm not thinking of?

Or have I totally misread the situation in some way?

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Review] SE-0052: Change IteratorType post-nil guarantee

2016-04-29 Thread Brent Royal-Gordon via swift-evolution
>   * What is your evaluation of the proposal?

I think it's a good idea.

This is a particularly sharp edge in the standard library: people have a 
completely reasonable expectation about `next()`'s behavior which is usually, 
but not always, borne out. And the vast majority of iterators can provide this 
feature for free. Only a few would pay any price, and that price would be 
minimal—it could easily be the cheapest statements in the method.

Nor do I think the FuseIterator solution will actually help. If you know about 
FuseIterator, you don't really need it, because you know about `next()`'s nil 
behavior and can code around it. This is an attempt to protect the people who 
*don't* know about the problem.

There are languages so averse to trading anything for efficiency that they 
refuse to provide simple improvements to help with these kinds of issues. I 
don't think Swift should be one of them.

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

Yes.

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

I think so. One of the major themes of Swift 3 is cleaning up the standard 
library.

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

I haven't, but some of the previous discussions on this issue have brought up 
Rust, which uses the FuseIterator solution. It seems like a pretty lousy one to 
me.

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

Quick reading this time, but I participated the previous discussion.

-- 
Brent Royal-Gordon
Architechies

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


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread David Hart via swift-evolution
But Collection has to have an extension which explicitly mentions 
IndexingIterator:

extension Collection where Iterator == IndexingIterator {
/// Returns an iterator over the elements of the collection.
public func makeIterator() -> IndexingIterator {
return IndexingIterator(_elements: self)
}
}

And Array, for example, has to be explicit:

public typealias Iterator = IndexingIterator<${Self}>

So I still don’t see how defining:

associatedtype Iterator : IteratorProtocol = IndexingIterator

has created any default behaviour.

When you say "The fact that the compiler does not allow to use the inferred 
‘Foo' type actually looks like a bug to me.”, could you give me an example of 
how you would have imagined this default behaviour to work in the case of 
Array? Would have expected Array not to have to define its typealias?

David.

> On 29 Apr 2016, at 10:59, Dmitri Gribenko  wrote:
> 
> On Fri, Apr 29, 2016 at 1:50 AM, David Hart  > wrote:
>> Hi Dimitri,
>> 
>> Excuse me if I’m being dumb. I saw those example but I don’t understand
>> their use.
>> 
>> If I define a custom Collection, I still have the be explicit in the types I
>> use where associated types are expected. Because I need to be explicit, I
>> don’t understand how default associated types are used.
>> 
>> Default parameters seem clear to me:
>> 
>> func foobar(a: Int = 0) {}
>> foo() // implicit uses default value
>> foo(a: 1) // Explicit bypasses default value
>> 
>> But default associated types are not:
>> 
>> protocol Foobar {
>>associatedtype Foo = Int
>>func foobar(a: Foo)
>> }
>> 
>> class FoobarImpl : FooBar {
>>func foobar(a: Foo) {} // error: Use of undeclared type ‘Foo’ - there is
>> no such thing as an implicit use
>>func foobar(a: Double) {} // This works but is explicit
>> }
> 
> In a typical use, 'func foobar' would also be defaulted.  The
> Collection.Iterator associated type and the makeIterator() method are
> an example of this.
> 
> The fact that the compiler does not allow to use the inferred 'Foo'
> type actually looks like a bug to me.
> 
> Dmitri
> 
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j (j){printf("%d\n",i);}}} /*Dmitri Gribenko  >*/

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


Re: [swift-evolution] [Review] SE-0017: Change Unmanaged to use UnsafePointer

2016-04-29 Thread Haravikk via swift-evolution
> On 28 Apr 2016, at 19:10, Chris Lattner via swift-evolution 
>  wrote:
> 
>   * What is your evaluation of the proposal?

Positive, while working with pointers should be avoided, when you have no 
choice it’s better for them to be as easy as possible to minimise errors, even 
if we can’t eliminate them completely (since that’s the risk with pointers).

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

Yes. While the conversion is trivial, it’s annoying, and essentially involves 
redundant types, so it’s better to eliminate them entirely.

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

Yes. While Swift tries to avoid pointers, when they are needed they should be 
as simple and uncluttered as possible.

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

Quick skim, but it’s pretty self-explanatory.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Add Binary Search functions to SequenceType

2016-04-29 Thread Haravikk via swift-evolution
Actually, the binary search proposal settled on a definition of a partition 
point method (and probably a partition method as well) that provides the real 
implementation details anyway, so these could go ahead as-is. You’re right that 
the search methods themselves may prefer to wait, since .sort() will likely 
change to reflect the new strict ordering operator, in which case it makes 
sense to delay those to be consistent, but partitioning should be unaffected.

> On 28 Apr 2016, at 13:03, Jeff Hajewski via swift-evolution 
>  wrote:
> 
> Thanks for bringing this back into the spotlight Pyry. A few of us have been 
> working on this issue here:
> 
> https://github.com/lorenzoracca/Swift-binary-search 
> 
> 
> However we have sort of stalled as we have been unable to come up with a 
> unary approach that Dave suggested using just Bool return values. And of 
> course, as you say, the three case order enum would make this a trivial 
> problem.
> 
> I guess the question is, do we move forward without a unary implementation 
> and update if/when we get a three case Order enum or do we wait on a three 
> case Order enum and implement a fully generic version once?
> 
>  Jeff
> 
> On Thu, Apr 28, 2016 at 7:36 AM, Pyry Jahkola  > wrote:
> Bringing up this topic because it became relevant with Brent Royal-Gordon's 
> "[Idea] Bringing the partial/total ordering distinction into Comparable 
> ".
> 
> If the `<=>` operator with a return type of a three-case `enum Order`, you 
> can fully define the most generic versions of binary searches as:
> 
> lowerBound(compare: Self.Collection.Element -> Order) -> Index
> 
> etc.
> 
>> On 29 Mar 2016, at 13:43, Jeff Hajewski via swift-evolution 
>> > wrote:
>> 
>> I've responded below, but just for the sake of being explicit, this is 
>> roughly 
>> the signature for lowerBound, upperBound, and binarySearch I have in 
>> mind based on your comments of a unary predicate:
>> 
>> lowerBound(isOrderedBelow: Self.Collection.Element -> Bool) -> Index
>> upperBound(isOrderedBelow: Self.Collection.Element -> Bool) -> Index
>> binarySearch(isOrderedBelow: Self.Collection.Element -> Bool) -> Bool
>> 
>> That's the general structure - the key is that the exact same predicate is
>> used in all signatures. The predicate would be defined along the lines of
>> a binary predicate where one of the parameters is fixed as the search value.
>> The unary predicate could be formed along the lines of:
>> 
>> let binaryPred = { $0 < $1 }
>> let unnaryPred = binaryPred($0, value)
>> 
>> where value is the search value. The main point of illustrating that is that
>> once the unary predicate is defined, we can't change the position of the
>> search value within the predicate like they do in the C++ implementation.
> 
> You're right, there's no way a Bool-returning unary comparator could allow 
> you to implement anything but lowerBound. With a three-value result, however, 
> you've got all you need.
> 
> I've shamelessly plugged before but for the sake of proving a point, I'll do 
> it once more: I think this little library we did works as a good starting 
> point for a stdlib binary search API: 
> https://github.com/knomi/Allsorts/blob/master/Allsorts/BinarySearch.swift 
> 
> 
> — Pyry
> 
> ___
> 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] Requiring proactive overrides for default protocol implementations.

2016-04-29 Thread Matthew Judge via swift-evolution


> On Apr 28, 2016, at 20:51, Erica Sadun via swift-evolution 
>  wrote:
> 
> 
>> On Apr 28, 2016, at 6:44 PM, Andrew Bennett  wrote:
>> 
>> Hey, what annotations would I have in this case:
>> 
>> Module 1:
>> Type AType { func foo() { ... } }
>> Module 2:
>> import Module1
>> protocol A { func foo() {...default...} }
>> extension AType: A {}
> 
> No annotations. AType's implementation of foo is unrelated to its 
> conformance, which is satisfied by its existing foo method.
> 

How does this match the first line in your "Handling Changes" table?

(from your table, for reference)
Original:  Some  member implemented in type
Change:  Protocol adds that member
Outcome:  Must add 'required' to type implementation or rename member to avoid 
conflict

>> Also, for your alternatives section:
>> 
>> protocol A { func foo() {...default...} }
>> Type AType: A {
>> func A.foo() {...replacement...}
>> }
>> 
>> I actually prefer this alternative, I think it fixes many issues.
> 
> Protocol default implementations do not yet exist.  
> 
> In this second, you're suggesting instead of doing "override required", you 
> use a naming approach that ties the implementation the specific protocol. I'm 
> not really won over by this approach:
> 
> * It does clarify why the method is included
> * It does not clarify that the method overrides an existing implementation.
> * It could be more easily confused when members are required by multiple 
> protocols.
> 
> -- E
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 29, 2016 at 1:50 AM, David Hart  wrote:
> Hi Dimitri,
>
> Excuse me if I’m being dumb. I saw those example but I don’t understand
> their use.
>
> If I define a custom Collection, I still have the be explicit in the types I
> use where associated types are expected. Because I need to be explicit, I
> don’t understand how default associated types are used.
>
> Default parameters seem clear to me:
>
> func foobar(a: Int = 0) {}
> foo() // implicit uses default value
> foo(a: 1) // Explicit bypasses default value
>
> But default associated types are not:
>
> protocol Foobar {
> associatedtype Foo = Int
> func foobar(a: Foo)
> }
>
> class FoobarImpl : FooBar {
> func foobar(a: Foo) {} // error: Use of undeclared type ‘Foo’ - there is
> no such thing as an implicit use
> func foobar(a: Double) {} // This works but is explicit
> }

In a typical use, 'func foobar' would also be defaulted.  The
Collection.Iterator associated type and the makeIterator() method are
an example of this.

The fact that the compiler does not allow to use the inferred 'Foo'
type actually looks like a bug to me.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread David Hart via swift-evolution
Hi Dimitri,

Excuse me if I’m being dumb. I saw those example but I don’t understand their 
use.

If I define a custom Collection, I still have the be explicit in the types I 
use where associated types are expected. Because I need to be explicit, I don’t 
understand how default associated types are used.

Default parameters seem clear to me:

func foobar(a: Int = 0) {}
foo() // implicit uses default value
foo(a: 1) // Explicit bypasses default value

But default associated types are not:

protocol Foobar {
associatedtype Foo = Int
func foobar(a: Foo)
}

class FoobarImpl : FooBar {
func foobar(a: Foo) {} // error: Use of undeclared type ‘Foo’ - there is no 
such thing as an implicit use
func foobar(a: Double) {} // This works but is explicit
}

I just don’t see the implicit use of the default associated type.

David.

> On 29 Apr 2016, at 09:36, Dmitri Gribenko  wrote:
> 
> On Fri, Apr 29, 2016 at 12:25 AM, David Hart via swift-evolution
>  wrote:
>> I’ve taken some time to digest the current feedback and I’ve changed my 
>> mind. The syntax for adding constraints to a sub-protocol in the protocol’s 
>> definition where clause is starting to grow on me. Before I modify the 
>> proposal, I'd still like to understand something:
>> 
>> What is the use of declaring a default associated types with the `=` syntax 
>> in protocols? I’ve never used them and I don’t understand what they provide.
> 
> Please take a look at the Collection protocol
> (https://github.com/apple/swift/blob/master/stdlib/public/core/Collection.swift).
> 
> associatedtype Iterator : IteratorProtocol = IndexingIterator
> associatedtype SubSequence : IndexableBase, Sequence = Slice
> associatedtype Indices : IndexableBase, Sequence = DefaultIndices
> 
> Some collections want to customize these, but for simple ones the
> defaults are usually fine.
> 
> Dmitri
> 
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j (j){printf("%d\n",i);}}} /*Dmitri Gribenko */

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


Re: [swift-evolution] [Review] SE-0052: Change IteratorType post-nil guarantee

2016-04-29 Thread Gwendal Roué via swift-evolution

> Le 29 avr. 2016 à 08:18, Gwendal Roué  a écrit :
> 
>> The review of "SE-0052: Change IteratorType post-nil guarantee" begins now 
>> and runs through May 3. The proposal is available here:
>> 
>>  
>> https://github.com/apple/swift-evolution/blob/master/proposals/0052-iterator-post-nil-guarantee.md
>>  
>> 
> I'd thus […] support the following alternatives:
> 
> - the FuseIterator Patrick's proposal (and we could discuss its name).
> - a new StoppingIterator protocol which does explicitly provide the post-nil 
> guarantee. Algorithms could then use this guarantee.

Actually, a StoppingIterator protocol is not a good idea, because this concept 
should go up the type hierarchy up to Collection in order to let sequence and 
collection methods use static type information in order to choose the correct 
iterator algorithm.

I'd prefer a FuseIterator that eventually returns nil forever as soon as it 
underlying iterator returns nil. Yes, fuseIterator would not apply the "when 
calling next(), no preceding call to next() should have returned nil" 
precondition. This precondition would be removed from the Iterator 
documentation. The FuseIterator would be the easy-going iterator, the one that 
has no surprise, and makes it easy to write algorithms.

When one needs a "simple" iterator, one just has to derive a FuseIterator from 
it. Its implementation could look like:

struct FuseIterator : Iterator {
let baseNext: () -> Element?
var ended: Bool = false
init(_ baseIterator: I) {
var baseIterator = baseIterator
baseNext = { baseIterator.next() }
}
mutating func next() -> Element? {
if ended {
return nil
} else if let element = baseNext() {
return element
} else {
ended = true
return nil
}
}
}

We would maybe also need a FuseSequence, in order to iterate a wild base 
iterator with a `for` loop until its first nil.

Last, forgive my non-native English, but when I look at "fuse" in a Thesaurus, 
I don't quite see the meaning of "consume until first exhaustion". It looks 
like any one of "BoundedIterator", "ClosedIterator", "CompactIterator", 
"TerminatingIterator" would better communicate its nature. "ClosedIterator" 
looks like the new "ClosedRange" types introduced by SE-0065 and is my current 
favorite.

Gwendal Roué

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


Re: [swift-evolution] Extending init checks for property initialization

2016-04-29 Thread Vladimir.S via swift-evolution

On 29.04.2016 2:21, Howard Lovatt via swift-evolution wrote:

I like the `defer init` idea but suggest you have to explicitly call it at
the end of all the other non-convenience `init`s. The advantage of an
explicit call are two fold:

  1. It is obvious what is happening
  2. You can pass arguments


Like this idea very much. IMO it is important to see that "defer init" will 
be called at the end when we are looking at the code of init. Otherwise we 
need to don't forget that "defer init" could be also defined and are called 
at the end of this init.


P.S. Sorry for duplicate.



On Friday, 29 April 2016, Basem Emara via swift-evolution
> wrote:

I see what you’re saying and the forced optionals is pretty inconvenient.

As far as syntax, how about more of a “deferred” init that gets
triggered regardless like this:

defer init() {
// Always gets called no matter what designated init triggers
}

> On Apr 27, 2016, at 5:52 PM, Shannon Potter via swift-evolution
 wrote:
>
> Consider a relatively-common init pattern:
>
> class SomeViewController: UIViewController {
>
>// MARK: Properties
>
>private var videoPlayer: AVPlayer
>private var videoPlayerLayer: AVPlayerLayer
>
>// MARK: - Object Lifecycle
>
>override init(nibName: String?, bundle nibBundle: NSBundle?) {
>super.init(nibName: nibName, bundle: nibBundle)
>
>commonInitialization()
>}
>
>required init?(coder decoder: NSCoder) {
>super.init(coder: decoder)
>
>commonInitialization()
>}
>
>private func commonInitialization() {
>videoPlayer = AVPlayer(...)
>videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
>}
>
> }
>
> This does not work. Both properties are non-optional, and the
compiler complains that they are not initialized in either init method.
It seems rather common to want a single point of contact regarding
object initialization, regardless of the path taken to initialize that
object. Ideally, objects could all be funneled to one designated
initializer, but this isn’t always the case.
>
> What are people’s thoughts about either a specialized function that
is always called at the very end of each object’s lifecycle OR some
sort of attribute for a function that hints that the compiler should
follow it if called in an init function to check for property
initialization?
>
> func commonInit() {
>
> }
>
> or
>
> @extend_init private func commonInitialization() {
>
> }
> ___
> 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



--
-- Howard.


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


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


Re: [swift-evolution] Extending init checks for property initialization

2016-04-29 Thread Vladimir.S via swift-evolution
Can't see any significant extra overhead because of implicity unwrapped 
property for your code. Could you clarify?


As for "going away" - as I understand, just ImplicitlyUnwrappedOptional 
type itself will be removed, but not the "implicitly unwrapped" feature:
"Appending ! to the type of a Swift declaration will give it optional type 
and annotate the declaration with an attribute stating that it may be 
implicitly unwrapped when used."


So I still think right now the solution for your issue is implicitly 
unwrapped optional. But again, I 100% support the idea of "defer init", 
more specifically the idea of explicitly called "defer init" in other 
inits, if "defer init()" is defined.


On 29.04.2016 3:49, David Sweeris wrote:



On Apr 28, 2016, at 11:50 AM, Vladimir.S via swift-evolution 
 wrote:

I think I like this idea. It is clear that it is init() and 'defer' says that 
it is called at the end of each init. IMO we need exactly some kind of 'init' 
as only in init we can set un-initialized stored properties.

But, why implicitly unwrapped optionals are not solution here? I.e.


To avoid the extra overhead. Also, they’re sorta going away in Swift 3: 
https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md

- Dave Sweeris.


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


Re: [swift-evolution] [Pitch] Allow nested protocol declarations

2016-04-29 Thread Krishna Kumar via swift-evolution
Hey Brad

+1 I think this will make delegate controller pattern a lot more clean and 
readable.

I was thinking about other areas where this can be useful, and I thought it 
will be great for property injection from parent controller to children.

class ParentController{
protocol Injection: class{

}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let childVC = segue.destinationViewController as? Injection
...
}
}

class ChildController: ParentController.Injection{

}


Does this make sense?

-Krishna

> On Apr 28, 2016, at 10:45 PM, Brad Hilton via swift-evolution 
>  wrote:
> 
> Type nesting allows some convenient and straightforward semantics that we see 
> inside the Swift standard library such as views on String like 
> String.CharacterView, String.UnicodeScalarView, etc. However a protocol 
> cannot be nested in a type and gives a non-obvious error that the 
> “Declaration is only valid at file scope.” Just as other nested types allow 
> proper contextual scoping, a nested protocol could make a lot sense for a 
> number of patterns. For example, there are many “Delegate” protocols 
> throughout the Cocoa frameworks. Here’s a controller/delegate pattern before 
> and after type nesting:
> 
> // Without type nesting
> 
> protocol MyControllerDelegate : class {
> 
> }
> 
> class MyController {
> 
> weak var delegate: MyControllerDelegate?
> 
> }
> 
> // With type nesting
> 
> class MyController {
> 
> weak var delegate: Delegate?
> 
> protocol Delegate : class {
> 
> }
> 
> }
> 
> Though the change is mostly semantics, it does allow an explicit association 
> between My Controller and the Delegate instead of only a named association. 
> It also cleans up the module name space like other nested types and makes 
> associated protocols more discoverable in my opinion. 
> 
> I’d love to hear everyone’s thoughts.
> 
> Brad Hilton
> ___
> 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] More Powerful Constraints for Associated Types

2016-04-29 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 29, 2016 at 12:25 AM, David Hart via swift-evolution
 wrote:
> I’ve taken some time to digest the current feedback and I’ve changed my mind. 
> The syntax for adding constraints to a sub-protocol in the protocol’s 
> definition where clause is starting to grow on me. Before I modify the 
> proposal, I'd still like to understand something:
>
> What is the use of declaring a default associated types with the `=` syntax 
> in protocols? I’ve never used them and I don’t understand what they provide.

Please take a look at the Collection protocol
(https://github.com/apple/swift/blob/master/stdlib/public/core/Collection.swift).

associatedtype Iterator : IteratorProtocol = IndexingIterator
associatedtype SubSequence : IndexableBase, Sequence = Slice
associatedtype Indices : IndexableBase, Sequence = DefaultIndices

Some collections want to customize these, but for simple ones the
defaults are usually fine.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] multi-line string literals.

2016-04-29 Thread Cole Campbell via swift-evolution
I think the proposal is very clear on its intended scope.

I really like this idea. It's readable, and it's as simple and uncluttered as I 
think it could be while still allowing the tabbing of new lines. The one thing 
I dislike about multi line strings in Ruby is how you have to left align each 
new line, which can really disrupt the visual flow of your code, especially if 
you are several tabs of indentation deep.

I would love to see the addition (at some point) of the ability to escape all 
whitespaces preceding the new line, if that line does not begin with a quote 
and thus is meant to be a direct continuation of the preceding line. That way 
you could maintain your indentation without adding whitespaces between what are 
meant to be subsequent characters in the string literal.


On Apr 28, 2016, at 5:52 PM, Brent Royal-Gordon via swift-evolution 
 wrote:

>> Did you ever really use multiline string literals before?
> 
> Yes. I used Perl in the CGI script era. Believe me, I have used every quoting 
> syntax it supports extensively, including `'` strings, `"` strings, `q` 
> strings, `qq` strings, and heredocs. This proposal is educated by knowledge 
> of their foibles.
> 
> As outlined in the "Future directions for string literals in general" 
> section, I believe alternate delimiters (so you can embed quotes) are a 
> separate feature and should be handled in a separate proposal. Once both 
> features are available, they can be combined. For instance, using the 
> `_"foo"_` syntax I sketch there for alternate delimiters, you could say:
> 
>  let xml = _"
>  "
>  " 
>  " \(author)
>  " 
>  ""_
> 
> Basically, I am trying very, *very* hard not to let this proposal turn into 
> "here's a huge pile of random string literal features which will become a 
> giant catfight if we debate them all at once". Clearly this message is not 
> getting through, but I'm not sure how I should edit the proposal to make it 
> clear enough.
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution