Re: [swift-evolution] mutating/non-mutating suggestion from a Rubyist

2016-04-21 Thread Krishna Kumar via swift-evolution
Hey

I think adding “&” to methods will reduce the readability of the code. Also, 
keyword “mutating” makes it super clear and readable that my method is mutating 
the values.

1. mutating func add(value: Double){…}

2. func add&(value: Double){…}

I think it’s easy to skip the information encoded into the 2nd function which 
is this function is mutating a value as compared to 1st. When I read 1st 
function I start reading with keyword “mutating” making its intentions clear to 
me.

Also, it might become a symbol nightmare with following type signature of a 
function-

func nightmare&(title: String?) -> String? -> String?{…}

I can see the advantage of using “&” when calling a function. It makes clear at 
the call site that this method is mutating but still I don’t find eliminating 
“mutating” a good step for the reasons mentioned above.

Maybe we can think of some better solution.

Thanks

-Krishna

> On Apr 21, 2016, at 10:38 PM, Daniel Steinberg via swift-evolution 
>  wrote:
> 
> swift-evolution@swift.org 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Accepted] SE-0059: Update API Naming Guidelines and Rewrite Set APIs Accordingly

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

On 21.04.2016 6:57, Douglas Gregor wrote:



On Apr 19, 2016, at 12:41 AM, Vladimir.S  wrote:

Just wanted to go back to
Apply API Guidelines to the Standard Library  SE-0006
https://github.com/apple/swift-evolution/blob/master/proposals/0006-apply-api-guidelines-to-the-standard-library.md
for a second.

Just found out that this code is working in 3.0(mar 24):
var z1 = [3,2,1]
let z2 = z1.sort() // mutating method!
print(z2) // => ()

so.. is this a final implementation or we are expecting to have a lot of 
hard-to-find errors in our Swift 3.0 code if code written for previous Swift 
will be used(private lib/snippet/etc)?

Also, just interesting, are we all expecting libs like RxSwift and 
ReacriveCocoa will rename their methods accordingly to names changed in Swift 
3.0?


It definitely seems reasonable for us to warn on this kind of example, e.g., 
placing a Void result of a call to a mutating method in a variable. Can you 
file a ticket a bugs.swift.org? It would be a great starter bug.

- Doug



Ticket created. SR-1288





On 19.04.2016 0:18, Douglas Gregor via swift-evolution wrote:


Proposal
link: 
https://github.com/apple/swift-evolution/blob/master/proposals/0059-updated-set-apis.md


Hello Swift Community,

The review of SE-0059 "Update API Naming Guidelines and Rewrite Set APIs
Accordingly” ran from March 31...April 5, 2016. The proposal is *accepted*.

There was much debate, both before and during the review, over the
“InPlace” suffix/ “form” prefix, and at this point any answer will be
objectionable to some. The core team has opted to accept the proposal
as-is, keeping the “form” prefix to describe the mutating counterpart to an
operation naturally described by a noun (e.g., “formUnion” for the mutating
variant of “union”), for the reasons described in the proposal itself.
Thanks all for the spirited discussion!

- Doug


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





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


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

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

> On Apr 21, 2016, at 19:58, James Berry  wrote:
> 
> 
>> On Apr 21, 2016, at 6:13 PM, Jordan Rose via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>> 
>> On 'isLessThanOrEqual(to:)’: I agree with Xiaodi that the argument label is 
>> problematic here. I think the problem is that we have two prepositions that 
>> apply to the argument, and “pick the second one” leaves the base name 
>> feeling unbalanced. (Remember that we allow referring to a method by its 
>> basename alone when using it as a function value.)
> 
> Maybe: isLessThanOrEqualTo(value:) ??

At that point the argument label doesn’t add anything that isn’t already 
provided by the type.

"Otherwise, if the first argument forms part of a grammatical phrase, omit its 
label."

The “otherwise” comes after "When the first argument forms part of a 
prepositional phrase”, but in this case it forms part of two prepositional 
phrases.

Jordan

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


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

2016-04-21 Thread James Berry via swift-evolution

> On Apr 21, 2016, at 6:13 PM, Jordan Rose via swift-evolution 
>  wrote:
> 
> On 'isLessThanOrEqual(to:)’: I agree with Xiaodi that the argument label is 
> problematic here. I think the problem is that we have two prepositions that 
> apply to the argument, and “pick the second one” leaves the base name feeling 
> unbalanced. (Remember that we allow referring to a method by its basename 
> alone when using it as a function value.)

Maybe: isLessThanOrEqualTo(value:) ??



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


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

2016-04-21 Thread Jordan Rose via swift-evolution
[Proposal: 
https://github.com/apple/swift-evolution/blob/master/proposals/0067-floating-point-protocols.md
 
]

This is super impressive. I do have several bits I’m uncomfortable with, 
however. I’ll try to separate that into “semantic” and “naming” sections.

Semantic

static var radix: Int { get }

Does it ever make sense to have a model type that allows different instances to 
have different radices?

Is there an algorithm that makes use of a model’s radix, or is this just in 
here for “completeness”?


  /// A signaling NaN (not-a-number).
  @warn_unused_result
  static func signalingNaN: Self { get }

I’m not sure it really makes sense for a Bignum / APFloat type to support such 
a value. But really I think this is just underspecified. What does it mean, in 
terms of this protocol and its uses, for a NaN to be signaling? Is it just a 
specific “color" of NaN, with no semantic requirements other than being 
distinguishable?

(Also, is ‘signalingNan.isNan’ true? I assume so but since ’nan’ is implied to 
be a non-signaling NaN I’m not sure anymore.)


  var signBit: Bool { get }

Unlike Chris, I’m strongly against this property as it stands. You should not 
be able to write “if someValue.signBit”; a bit is not a boolean value. 
(Citation: "Uses of Boolean methods and properties should read as assertions 
about the receiver 
.”)

I’d be okay with Greg’s idea of changing the type to an enum. I’d also be okay 
with renaming this to a predicate, whatever the name ends up being. 
(“isSignBitSet”, “isSignNegative”, etc.)


  var exponent: Int { get }

Nitpick: it’s probably worth noting in the doc comment that this is the 
unbiased exponent value.

Also, does it matter that this is insufficient for bignums, which may have an 
exponent of greater than `sizeof(Int.self)` bits? (This is also a concern for a 
number of members of BinaryFloatingPoint, like ‘significantBitCount'.)


Naming

On “NaN” vs. “Nan”: I’m not convinced that ignoring the case is the right way 
to go here. IMHO the clearest lowercase form is “nan” and the clearest 
capitalized form is “NaN”.

The current draft API guidelines 
 
don’t cover this case, but if I were to add something for this, I’d say “when a 
word is normally written with mixed case, the lowercase form should be 
fully-lowercased if the first letter is naturally uppercase, and the 
capitalized form should have the first letter uppercased only.” That rule 
produces “iPhone/IPhone”, “next/NeXT”, and “nan/NaN”. (The “if the first letter 
is naturally uppercase” could be thrown out as well.)


On 'isLessThanOrEqual(to:)’: I agree with Xiaodi that the argument label is 
problematic here. I think the problem is that we have two prepositions that 
apply to the argument, and “pick the second one” leaves the base name feeling 
unbalanced. (Remember that we allow referring to a method by its basename alone 
when using it as a function value.)


On 'isTotallyOrdered(with:)’: I lost track of who said it, but I agree that 
this sounds like it’s “!isUnordered(with: other)”. The only name that’s coming 
to mind is ‘isTotallyOrderedBefore(_:)’, which isn’t great.


On ‘binade’: At first I thought this was a confusing term and there had to be a 
better one, but now I think it’s an “if you don’t know what this is, you don’t 
need to use it” case. :-)


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


Re: [swift-evolution] Notes from Swift core team 2016-04-20 design discussion

2016-04-21 Thread David Waite via swift-evolution

> On Apr 21, 2016, at 9:58 AM, Alex Martini via swift-evolution 
>  wrote:

> What to do about optional requirements

> http://thread.gmane.org/gmane.comp.lang.swift.evolution/14046 
> 
> Rename it to make it clearly an Objective-C interop feature. We could also 
> forbid you actually spelling it in Swift code. That doesn’t work well because 
> it breaks your ability to write code in Swift that has Objective-C clients — 
> those clients won’t get the default implementation from the extensions like 
> you would use with Swift clients instead of creating optional requirements.
> Modeling optional requirements as a function of optional type such as ((A, B) 
> -> C)? doesn’t work well. For example, properties can have optional type and 
> they can be optional requirements, so you would end up having to deal with a 
> lot of extra complexity due to double-optionals and likely want better code 
> completion so you could type it all out.
> You force the default implementation to be visible from all callers, and you 
> do the dispatch at the call site. The only advantage of this is that it takes 
> optional requirements out of the language entirely. If you wanted to 
> implement the (somewhat common) pattern of checking whether a type implements 
> an optional requirement, you would have to use a respondsToSelector check.
Calling an optional method on a delegate protocol and using the result to judge 
whether you should have some default behavior to me does seem a bit flimsy in 
retrospect (I originally proposed things like importing optional methods with 
throws and having an unimplemented method error raised by default, etc). You 
aren’t really trying to judge that the behavior ‘currently’ is the default, but 
that there is no behavior defined thus you can reliably *always* use the 
default.

To that end, you need some way to detect static features of a type at runtime. 
Today we have respondsToSelector for objc types, and checking for conformance 
to different protocols.

I don’t think supporting optional protocols in swift could work unless there 
was also a respondsToSelector equivalent for native swift types.

-DW



signature.asc
Description: Message signed with OpenPGP using GPGMail
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Accepted, pending implementation] SE-0054: Abolish ImplicitlyUnwrappedOptional type

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

on Thu Apr 21 2016, Chris Willmore  wrote:

> I evaluated the effects of this proposal on five projects written in Swift
> against Foundation and other well-audited OS X and iOS Objective-C APIs. The
> only changes that had to be made were the result of Objective-C API in the
> project itself that had not yet been annotated with nullability information. 
> In
> addition, it ended up revealing a programming error in one project where a
> property had been unintentionally inferred to have IUO type. I presented these
> results at the Swift core team review meeting.
>
> Jordan Rose expressed some concern that this sampling of projects didn’t 
> really
> say anything about the effect of these changes on projects that depend on
> unaudited API, especially the Linux case. So I investigated the effect of this
> proposal on building swiftpm, which makes extensive use of POSIX C API. It 
> ended
> up requiring ten new uses of the ! operator (out of 14k lines of Swift) to get
> building again; they were all return values from C API (ctime_r, getcwd, 
> getenv,
> strerror, realpath) that had been saved to intermediate variables. Jordan
> observes that most of the cases are better expressed with “if let” or “guard
> let” statements anyway.
>
> We have concluded that we should move forward with implementing the
> proposal.

NICE!

-- 
Dave

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


Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread Niall Young via swift-evolution

On Thu, 21 Apr 2016 James Froggatt  wrote:


Could traits be constructed from protocol extensions in this way, or otherwise 
end up competing with them if just some of these features were to be added? My 
concern is that adding traits as a separate language feature could put them in 
direct competition with protocol extensions.


They should definitely be some _form_ of protocol extension, just the rules 
around their consumption would be different to the current constraint of static 
vs. dynamic dispatch.

Traits could be a second example of the underlying Type behind Extensions, or 
Trait functionality could be added to Extensions directly in terms of how they 
are consumed, how conflicts are resolved, and how dynamic vs. static dispatch 
is handled, independent of any consumer-level requirements or rules.

--
Niall Young
ni...@iinet.net.au
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread Niall Young via swift-evolution

On Thu, 21 Apr 2016, David Waite wrote:


Think of a Trait as providing a consumable set of functions.  Now imagine that 
we're combining the collective declarations of 1..N Traits all together, 
consumed by a Class or Value Type (or Protocol!) in a predicable and safe way 
(flattening: see the first Traits white paper).


extensions give us something trait-like, but with only one, non-opt-in 
implementation and usually per protocol. I’d imagine a true trait system to 
allow for more specific default implementations of Sequence, for example.


Exactly, Sequence protocol requirements could be met and provided directly by any 
Trait(s) consumed by the protocol as default implementation(s), or consumed by a Class or 
Value Type to partially or fully meet its protocol conformance requirements.  
Fine-grained Traits of behaviour could be consumed in many different contexts, so it's 
similar in some respects to AOP in that the code relating to that "aspect" or 
behaviour is centralised into a composable entity which any class, value type or protocol 
could consume and use.


with a Trait being a closure, where _only private_ data Properties can be 
declared, providing 1..N function implementations.  It could conform _towards_ 
a Protocol (partial to full conformance), and also be dependent upon other 
names Traits, which would be consumed in parallel as a first-class citizen with 
the Trait that depends on it.


Traits typically cannot declare fields/state. Is this not where you start to 
cross over to Mixins?


The Stateful Traits papers have explored the issues with introducing state on 
top of behaviour, but a simple solution to avoid this complexity is to not 
allow state period, or keep all state private to the Trait and never visible to 
any Trait consumer.  I wouldn't necessarily mandate that Traits for Swift 
should or could deal with state, they could be method-only behaviours and 
side-step these issues entirely, declaring their own requirements in terms of 
state that the consumer must provide, for example, or adherence to a protocol 
that the consumer must satisfy.


I attempted to model this (today) via delegates for behavioral dependencies on 
traits and self-wiring, but this creates issues with value type copying and 
circular references in reference types. For that reason, I didn’t feel it was 
appropriate to make a formal trait proposal until more definition toward 
behaviors (e.g. Joe Groff’s property behaviors) or macros were in the 
discussion.


I'll do some reading - was this a previous swift-evolution thread?  I've not 
started looking at Swift's own implementation, so I haven't thought out exactly 
how they could be implemented, but on the surface at a syntactic and feature 
level it seems like a good fit for Swift and a perfect complement to protocols, 
enabling fine-grained code re-use with inherent predictability and safety.




Stateful Traits suggest that as long as the data is private _to the Trait_ then 
we can safely ignore some of the complexity of state in Traits - it just isn't 
exposed as the Trait declaration itself is a closure.  Dependency on state in 
the consumer could proxy to class/instance/value-type data via Protocol.


Yes, but this means that said data may be duplicated and need to be kept in 
sync between traits and the main type. It also means that traits cannot be used 
while extending an existing type to meet new protocol requirements outside a 
module, as that may change the size of the type itself to be different than 
what precompiled code expects.


If I understand you correctly (please elaborate if I don't :)) the data that a Trait owns would 
never be visible to any consumer, other Trait(s), or any other instance where that same Trait has 
been consumed.  It wouldn't necessarily need to be stored against the consuming Type, only made 
visible to that specific Trait "instance" for use by its methods.  Trait data wouldn't be 
shared with any other code, the consumer or even other "instances" of that Trait being 
consumed elsewhere, so I think of it more as lexically scoped private variables - similar to 
contextual data visible to a closure, yet no other code will be able to see or access them.  It 
wouldn't necessarily need to be stored with the consuming Type, but I don't know if that's even 
feasible or desirable yet.

Exactly how Traits could be implemented under the hood for Swift - I'll do some 
reading and walk through the source, but others would be better placed to 
comment on the feasibility of this right now.  I'm curious, so I'll see what I 
can come up with on my own.

Cheers,

--
Niall Young
ni...@iinet.net.au___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] Enhanced floating-point protocols

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

on Thu Apr 21 2016, Thorsten Seitz  wrote:

> I totally agree with you. 
>
> But I think that the suggested Summable with zero fits the bill of
> your citation quite nicely as it actually is a very generic concept
> which is widely useful.

Sure, that's Monoid.  My main objection is to adding a "Multiplicative"
that doesn't actually have two operations with the right relationships.

I'm trying to explain general principles here, not pick on Summable
specifically.  The main reason not to add Summable is that once you
attach numeric semantics to the operation of Monoid, there are no useful
models I know of that can't also satisfy some much richer protocols such
as Arithmetic.

> FWIW I had chosen the name Summable instead of Monoid for two reasons: (1) 
> there
> has been reluctance by some people on this list to add algebraic types to the
> standard library

Yeah, we're reluctant because we want to do it right and that's hard.

> and (2) Summable is one concrete instance of Monoid for numbers (with
> respect to addition) just as my other suggestion Multiplicative is
> another instance of Monoid for numbers (with respect to
> multiplication).

Yeah... having a system where some things conform to the same protocol
in multiple ways is a whole 'nother kettle of fish that needs its own
language features
(c.f. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2098.pdf)

> If we want to add Monoid (and other algebraic types) to the standard
> library (I would welcome that), you are certainly right that we should
> design this well.  

We should design it well even if we're going to stick to numerical
subsets of Monoid ;^)

> The above actually suggests that summable and multiplicative instances
> for numbers might just be that: (singleton?)  instances of Monoid with
> an associated type of Number (instead of protocols) so that they can
> be passed around more easily.  

I don't know what you have in mind here.

> On the other hand we could borrow some ideas from Eiffel to solve the
> (semantic) diamond problem via renaming and choosing defaults. Like
> the early work about generics you found, 

I don't mean to be a pedant, but what I pointed you about is not about
generics, which is a collection language features.  Generics had been
around for years in Ada and C++ when that was written.  That paper is
about *generic programming*, which I won't define here because the paper
does a much better job than I can.

> Eiffel's solution sadly is ignored in most language designs (and
> interfaces thought of as a solution of the diamond problem... they are
> not). Not too long ago I wrote a lenghty mail on this list about that
> in the Mixin thread IIRC.
>
> I'm not sure I'm adding anything by saying this, but one problem with
> creating protocols that satisfy the absolute minimum requirements for a
> particular algorithm is that you end up without any meaningful
> abstractions.
>
> I think Dave Sweeris' example is not about creating Addable a.k.a
> Summable just because it satisfies the algorithm but rather it happens
> that Monoid *is* such a useful abstraction that it naturally pops up
> in many algorithms.

Why do you think that?  It seemed pretty well focused around addition to
me.

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


Re: [swift-evolution] [Accepted, pending implementation] SE-0054: Abolish ImplicitlyUnwrappedOptional type

2016-04-21 Thread Chris Willmore via swift-evolution
I evaluated the effects of this proposal on five projects written in Swift 
against Foundation and other well-audited OS X and iOS Objective-C APIs. The 
only changes that had to be made were the result of Objective-C API in the 
project itself that had not yet been annotated with nullability information. In 
addition, it ended up revealing a programming error in one project where a 
property had been unintentionally inferred to have IUO type. I presented these 
results at the Swift core team review meeting.

Jordan Rose expressed some concern that this sampling of projects didn’t really 
say anything about the effect of these changes on projects that depend on 
unaudited API, especially the Linux case. So I investigated the effect of this 
proposal on building swiftpm, which makes extensive use of POSIX C API. It 
ended up requiring ten new uses of the ! operator (out of 14k lines of Swift) 
to get building again; they were all return values from C API (ctime_r, getcwd, 
getenv, strerror, realpath) that had been saved to intermediate variables. 
Jordan observes that most of the cases are better expressed with “if let” or 
“guard let” statements anyway.

We have concluded that we should move forward with implementing the proposal.
  
-- Chris Willmore

> On Mar 31, 2016, at 9:43 AM, Chris Lattner via swift-evolution 
>  wrote:
> 
> Proposal Link: 
> https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md
> 
> The review of SE-0054 "Abolish ImplicitlyUnwrappedOptional type" ran from Mar 
> 25…30, 2016. The proposal has been *accepted, pending implementation 
> experience*:
> 
> There is generally positive feedback on the proposal, as it keeps the good 
> behaviors of the existing T! type syntax (including support for importing 
> un-nullability-audited APIs, support for 2-phase initialization patterns, 
> etc) while dramatically reducing the confusion and surprise that they 
> introduce as they trickle through type inference.  The core team sees 
> significant value in having a simple and predictable model that can be 
> explained concisely. 
> 
> That said, this is the sort of proposal that can have a profound impact on 
> the actual experience using unaudited APIs.  The core team believes that the 
> experience will be good, but we would like to get some experience moving a 
> couple of existing projects (both low-level code that interacts with C, and 
> an “App” project working with high level frameworks) to see what the impact 
> is in practice.  If something unexpected comes up, we will revisit this, and 
> potentially reject it later.  Chris Willmore is working on an implementation 
> of this now, so we should know in the next week or two.
> 
> Thank you to Chris Willmore for driving this forward!
> 
> -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] [Proposal draft] Enhanced floating-point protocols

2016-04-21 Thread Thorsten Seitz via swift-evolution
I totally agree with you. 

But I think that the suggested Summable with zero fits the bill of your 
citation quite nicely as it actually is a very generic concept which is widely 
useful. 

FWIW I had chosen the name Summable instead of Monoid for two reasons: (1) 
there has been reluctance by some people on this list to add algebraic types to 
the standard library and (2) Summable is one concrete instance of Monoid for 
numbers (with respect to addition) just as my other suggestion Multiplicative 
is another instance of Monoid for numbers (with respect to multiplication).

If we want to add Monoid (and other algebraic types) to the standard library (I 
would welcome that), you are certainly right that we should design this well. 
The above actually suggests that summable and multiplicative instances for 
numbers might just be that: (singleton?) instances of Monoid with an associated 
type of Number (instead of protocols) so that they can be passed around more 
easily. 
On the other hand we could borrow some ideas from Eiffel to solve the 
(semantic) diamond problem via renaming and choosing defaults. Like the early 
work about generics you found, Eiffel's solution sadly is ignored in most 
language designs (and interfaces thought of as a solution of the diamond 
problem... they are not). Not too long ago I wrote a lenghty mail on this list 
about that in the Mixin thread IIRC.

> I'm not sure I'm adding anything by saying this, but one problem with
> creating protocols that satisfy the absolute minimum requirements for a
> particular algorithm is that you end up without any meaningful
> abstractions.

I think Dave Sweeris' example is not about creating Addable a.k.a Summable just 
because it satisfies the algorithm but rather it happens that Monoid *is* such 
a useful abstraction that it naturally pops up in many algorithms.

-Thorsten 

> Am 21.04.2016 um 20:36 schrieb Dave Abrahams via swift-evolution 
> :
> 
> 
> on Wed Apr 20 2016, davesweeris-AT-mac.com wrote:
> 
>>> On Apr 20, 2016, at 1:15 PM, Dave Abrahams via swift-evolution 
>>>  wrote:
>>> 
>>> 
 on Tue Apr 19 2016, Thorsten Seitz  wrote:
 
 I'd like to have something like Summable with 'add', 'adding' and 'zero' 
 being a
 separate protocol as well as somthing like Multiplicative with 'multiply',
 'multiplied' and 'one' being a separate protocol, because these are 
 universally
 interesting for other cases, e.g. Summable would be useful for defining 
 path
 lengths in a graph library.
 
 Would you mind adding that to the proposal?
>>> 
>>> I suspect you may be headed into the realm of
>>> protocols-as-bags-of-syntax.
>> 
>> You say that like it’s a bad thing… 
> 
> Indeed!
> 
>> Am I missing the point? (NOT a rhetorical question)
> 
> I don't know, but I'll try to help answer...
> 
>> Speaking only for myself, I want stuff broken up into many simpler
>> protocols (which `Arithmetic` and such conform to) because there are
>> many algorithms which only require small parts of the larger
>> protocol. What if I wanted to add a function that sums all the
>> elements in a collection?
>> 
>> extension CollectionType where Generator.Element: Arithmetic {
>>func sum() -> Generator.Element {
>>var s = Generator.Element()
>>for e in self {
>>s.add(e)
>>}
>>return s
>>}
>> }
>> 
>> Yeah, it works, but if I want to get the sum of a collection of some custom 
>> type, I
>> have to implement *all* of `Arithmetic`, as opposed to just the two
>> parts of it (`init()` and `.add(:)`) that the algorithm actually
>> uses. It’d be both simpler for the users and *more to the point of the
>> function*, if it could be written like this:
>> 
>> extension CollectionType where Generator.Element: Addable { // "Addable" 
>> instead of "Arithmetic"
>>... // No change here
>> }
> 
> This method is undocumented.  What does it *do*, given an arbitrary
> element type conforming to Addable?  The answer needs to be a
> description of the semantics that doesn't require me to effectively
> execute the source of the function in my head.  How can I test that the
> method does the right thing?  To answer these questions, you have to
> attach some semantics to Addable so that it's more than a mere bag of
> syntax.  For example, for the above to produce the usual semantics of
> summing, the Element's init() method needs to produce the additive
> identity element.
> 
> Choosing the granularity of protocols is something of an art.  Lots has
> been written about generic programming's “requirement minimization
> principle,” in which the more requirements you add, the less reusable
> algorithms become.  Almost nothing has been written about the other side
> of the coin, but...
> 
> After much googling I came up with a reference to one of Alexander
> Stepanov and James Dehnert's early papers on generic programming (it
> sometimes amazes me how many of the key insights can only be found in
>

[swift-evolution] [Draft Proposal for pre discussion]NS_ENUM's should be considered Open

2016-04-21 Thread Joseph Lord via swift-evolution
Can I get some thoughts about this idea to remove undefined behaviour 
from switch statements when an enum imported from Objective-C has a raw 
value outside the expected set?


The proposal is on my fork and below: 
https://github.com/josephlord/swift-evolution/blob/master/proposals/-consider_ns_enums_open.md


Thanks,

Joseph

# NS_ENUMs should be considered Open

* Proposal: 
[SE-](https://github.com/josephlord/swift-evolution/blob/master/proposals/-consider_ns_enums_open.md)

* Author(s): [Joseph Lord](https://github.com/josephlord)
* Status: [Early Draft]
* Review manager: TBD

## Introduction

Enums imported from C/Objective C could (as a result of library 
versioning or bugs) actually have raw values outside of the defined 
values. A default case should be required on switch statements involving 
them and the current undefined behaviour should be removed.


Swift-evolution thread: [To be filled in after discussion]

## Motivation

In cases where an enum value is outside of the expected range and there 
is no default in a switch the behaviour is currently undefined (it seems 
to take the first case in practice) potentially leading to runtime 
crashes. Undefined behaviour and crashes at runtime due to library 
changes outside the developer's control are highly undesirable and Swift 
should be helping us to make safe code to prevent them. At the moment if 
you are handling all cases it is not even possible to add a default case.


I encountered the issue when testing on iOS 8 and hitting [an issue with 
CoreData](http://stackoverflow.com/a/32978387/1476206) where it was 
passing a zero value the NSFetchedResultsChangeType to my code. That 
thread clearly shows that the issue is affecting people and while it is 
clearly a bug in the unsafe code of Core Data that is something which 
Swift should be defending against. There is a simple test example 
showing the issue in [SR-1258](https://bugs.swift.org/browse/SR-1258)


## Proposed solution

Redefine NS_ENUMs from being a closed type to an open one. This would 
then require a default case on all switch statements over the type. With 
the default case explicit situation must be handled by the developer. 
They can choose to raise errors call assertionFailure or 
preconditionFailure as the wish or handle the case safely.


## Detailed design

 - Help required here

## Impact on existing code

This will break all switch statements over an enum imported from 
Objective-C or C where there is no default case. There should not be any 
automatic migration because it is appropriate for the developer to 
decide on the course of action in each case.


## Alternatives considered

1) No change

This leaves the potential for undefined behaviour in all build modes if 
cases of bugs in code outside of Swift OR in the event that new cases 
are added to enums in future library versions.


2) Debug assertion

This would have the benefit that developers might discover errors more 
quickly but could still leave risks where libraries (including OS 
frameworks) are updated and introduce bugs after application release or 
in untested configurations.

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


Re: [swift-evolution] [Idea] Passing an Array to Variadic Functions

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

on Thu Apr 21 2016, Jeremy Pereira  wrote:

>> On 20 Apr 2016, at 19:24, Dave Abrahams via swift-evolution 
>>  wrote:
>> 
>> 
>> on Wed Apr 20 2016, Tino Heth  wrote:
>> 
>>> Increment/decrement operators, currying, tuple splat and even the
>>> C-style for loop have already been deprecated, and although I would
>>> have preferred to keep some of those constructs, I think it is good
>>> how progressive Swift is pushed forward ("would we add this feature
>>> now if it wasn't already there?").
>> 
>> We're in a stage of Swift's development where we can ask this question
>> fairly freely,
>
> I think we are already past that stage, whether we like it or
> not. There is already quite a lot of Swift code in “production” and
> some people in the wider community are already resenting some of the
> removals.

That may be so, but we are explicitly giving ourselves license to ask
these kinds of questions now because we expect it to become much harder
in the future.

-- 
Dave

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


Re: [swift-evolution] [Proposal draft] Enhanced floating-point protocols

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

on Wed Apr 20 2016, davesweeris-AT-mac.com wrote:

>> On Apr 20, 2016, at 1:15 PM, Dave Abrahams via swift-evolution 
>>  wrote:
>> 
>> 
>> on Tue Apr 19 2016, Thorsten Seitz  wrote:
>> 
>>> I'd like to have something like Summable with 'add', 'adding' and 'zero' 
>>> being a
>>> separate protocol as well as somthing like Multiplicative with 'multiply',
>>> 'multiplied' and 'one' being a separate protocol, because these are 
>>> universally
>>> interesting for other cases, e.g. Summable would be useful for defining path
>>> lengths in a graph library.
>>> 
>>> Would you mind adding that to the proposal?
>> 
>> I suspect you may be headed into the realm of
>> protocols-as-bags-of-syntax.
>
> You say that like it’s a bad thing… 

Indeed!

> Am I missing the point? (NOT a rhetorical question)

I don't know, but I'll try to help answer...

> Speaking only for myself, I want stuff broken up into many simpler
> protocols (which `Arithmetic` and such conform to) because there are
> many algorithms which only require small parts of the larger
> protocol. What if I wanted to add a function that sums all the
> elements in a collection?
>
> extension CollectionType where Generator.Element: Arithmetic {
> func sum() -> Generator.Element {
> var s = Generator.Element()
> for e in self {
> s.add(e)
> }
> return s
> }
> }
>
> Yeah, it works, but if I want to get the sum of a collection of some custom 
> type, I
> have to implement *all* of `Arithmetic`, as opposed to just the two
> parts of it (`init()` and `.add(:)`) that the algorithm actually
> uses. It’d be both simpler for the users and *more to the point of the
> function*, if it could be written like this:
>
> extension CollectionType where Generator.Element: Addable { // "Addable" 
> instead of "Arithmetic"
> ... // No change here
> }

This method is undocumented.  What does it *do*, given an arbitrary
element type conforming to Addable?  The answer needs to be a
description of the semantics that doesn't require me to effectively
execute the source of the function in my head.  How can I test that the
method does the right thing?  To answer these questions, you have to
attach some semantics to Addable so that it's more than a mere bag of
syntax.  For example, for the above to produce the usual semantics of
summing, the Element's init() method needs to produce the additive
identity element.

Choosing the granularity of protocols is something of an art.  Lots has
been written about generic programming's “requirement minimization
principle,” in which the more requirements you add, the less reusable
algorithms become.  Almost nothing has been written about the other side
of the coin, but...

After much googling I came up with a reference to one of Alexander
Stepanov and James Dehnert's early papers on generic programming (it
sometimes amazes me how many of the key insights can only be found in
that early work):

http://www.stepanovpapers.com/DeSt98.pdf

  We call the set of axioms satisfied by a data type and a set of
  operations on it a concept. Examples of concepts might be an integer
  data type with an addition operation satisfying the usual axioms; or a
  list of data objects with a first element, an iterator for traversing
  the list, and a test for identifying the end of the list. **The critical
  insight which produced generic programming is that highly reusable
  components must be programmed assuming a minimal collection of such
  concepts, and that the concepts used must match as wide a variety of
  concrete program structures as possible**. Thus, successful production
  of a generic component is not simply a matter of identifying the
  minimal requirements of an arbitrary type or algorithm – it requires
  identifying the common requirements of a broad collection of similar
  components. The final requirement is that we accomplish this without
  sacrificing performance relative to programming with concrete
  structures. A good generic library becomes a repository of highly
  efficient data structures and algorithms, based on a small number of
  broadly useful concepts, such that a library user can combine them and
  his own components in a wide variety of ways.

(emphasis mine).

I'm not sure I'm adding anything by saying this, but one problem with
creating protocols that satisfy the absolute minimum requirements for a
particular algorithm is that you end up without any meaningful
abstractions.

“*The* critical insight,” wow.  And it's so easily overlooked.

HTH,

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


Re: [swift-evolution] [Review] SE-0068: Expanding Swift Self to class members and value types

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

> On Apr 20, 2016, at 11:16 AM, Chris Lattner via swift-evolution 
>  wrote:
> 
> Hello Swift community,
> 
> The review of "SE-0068: Expanding Swift Self to class members and value 
> types" begins now and runs through April 25. The proposal is available here:
> 
>   
> https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
>  
> 


RELATED DISCUSSIONS

* Design Team feedback 
 on SE-0068
* [Pitch] Adding a Self type name shortcut for static member access 

* [Pitch] Rename `x.dynamicType` to `x.Self` 

* Making `.self` after `Type` optional 

* Remove the Need for 'self' to Access 'dynamicType' 


SHOULD .self BE REMOVED FROM TYPES

Design team notes say:

We have a proposal to remove .self on types. One reason .self exists is to 
avoid the mistake of writing let x = Int — the compiler will give you a weird 
type error later on in code if the value of x is what we today call Int.self 
but you meant to call the Int() initializer. Creating a metatype is not a 
common operation, so doing it explicitly is a good thing.

Coming back to this proposal, if we removed .self why would we want to add 
.Self?

Background:
>From Joe Groff: "`.self` is also a bit of load-bearing duct-tape that 
>currently supports some other parsing aspects of Swift's syntax." 
Jordan Rose adds, "Swift's type-checking engine is strong enough to merit not 
needing the redundant `.self` safety check." 

I personally like distinguishing `Type.self` from raw `Type` use for the 
reasons stated. This feature affirmatively prevents the use of `Typename` when 
`Typename()` is meant. In terms of this proposal, can this and should this be  
retained in the language but renamed from `self`? That would update the quiz to:

Self. // T.Type
self.Self   // T.Type
Self.Self   // T.Type.Type
self. // == self
Which reduces at least some of the confusion. The actual runcible name could be 
bikeshedded.

IS `Self` THE RIGHT NAME? / SHOULD `dynamicType` require `self`

I like `Self`.  It is an existing keyword. It matches the approach used in 
protocols where `Self` is a placeholder for the type that conforms to that 
protocol. Under SE-0068, it refers to the dynamic type of the current instance. 
If it has to be a choice of one or the other, I'd prefer renaming `.self` and 
retaining `Self`. If `Self` is not the right name, I'd recommend either the 
`dynamictype` keyword and dropping the `self` prefix requirement or using a 
freestanding `dynamicType()` call. 

We have one keyword left in the language, dynamicType, which is camel cased. 
This proposal renames it to Self instead.

Why don’t we turn this into a standard library function? It’s not something you 
need so often that the member access is very valuable. Putting it in the 
standard library as dynamicType(_:) does still allow for that function to be 
implemented using compiler magic.

Another approach would be to introduce a new dynamictype keyword that doesn’t 
need to be accessed as a member of self, and keep Self the way it is.  Self 
should work in structs as a type alias.

Another perspective is that .dynamicType is just an implicitly synthesized 
property on all type.

Subjectively, having dynamicType as a member feels weird.

If retained as a keyword, I believe it should be lowercased to `dynamictype`. 
This leaves two remaining outliers (`willSet` and `didSet`). If it is 
re-introduced as a stdlib function, it should be `dynamicType()`.

--

ORIGINAL DESIGN TEAM FEEDBACK
SE-0068: Expanding Swift Self to class members and value types 

https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
 

We have one keyword left in the language, dynamicType, which is camel cased. 
This proposal renames it to Self instead.

In a static function today, self.dynamicType will give you a metatype but the 
non-member Self will not. The most useful reason to reference it is to call an 
initializer. It makes accessing the metatype weirder. It’s not Self.Type; 
that’s a type — you have to spell it Self.type.

Quiz time! What do each of the permutations mean?

Self.self
self.Self
Self.Self
self.self
The number of capital letters gives you the level of meta-ness. This is very 
subtle, which is probably not a good thing.

Another approach would be to introduce a new dynamictype keyword that doesn’t 
need to be accessed as a member of self, and keep Self the way it is.  Self 
should work in structs as a type alias.

Why don’t we turn this into a standard li

Re: [swift-evolution] Notes from Swift core team 2016-04-20 design discussion

2016-04-21 Thread Vladimir.S via swift-evolution
"Another approach would be to introduce a new dynamictype keyword that 
doesn’t need to be accessed as a member of self, and keep Self the way it 
is.  Self should work in structs as a type alias."


So, could you clarify, do you suggest to introduce dynamictype keyword 
instead of "self.dynamicType" ? (In addition to remove .self on type and 
.Self for instance)


And to leave Self just as placeholder for current type i.e. "the class 
there this is declared"  ?


Just want to clarify. Let's review this code:

protocol Proto {
func z() -> Self
func z(s: Self)
}

class X: Proto {
required init () {}
func x() -> Self { return self.dynamicType.init() }
func z() -> Self { return self }
func z(s: X) {}
}


How should it looks like in Swift 3.0 ? :

protocol AP {
func z() -> dynamictype
func z(s: Self)
}

class X: AP {
required init () {}
func x() -> dynamictype { return dynamicType.init() }
func z() -> dynamictype { return self }
func z(s: X) {} // ? Don't we want to have Self here ?
}


Do you support to extend Self to be used in class methods declarations to 
behave just like in protocol i.e. as "placeholder for defined class" ?


So we can have in class:
func z(s: Self) {}

Do you support to rename Self -> #Self ?

Thank you for answers.


On 21.04.2016 18:58, Alex Martini via swift-evolution wrote:

To help keep proposals moving forward, the Swift core team has set aside
some time specifically for design discussions of upcoming proposals.  Below
are some rough notes from the yesterday's discussion.

These are informal comments, intended to guide the proposals in directions
that draw constructive feedback. You are welcome to ignore the
feedback, agree with it, or disagree with it.  As always, the formal
decision doesn't happen until after the review period ends.


  SE-0068: Expanding Swift Self to class members and value types

https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md

We have one keyword left in the language, dynamicType, which is camel
cased. This proposal renames it to Self instead.

In a static function today, self.dynamicType will give you a metatype but
the non-member Self will not. The most useful reason to reference it is to
call an initializer. It makes accessing the metatype weirder. It’s
not Self.Type; that’s a type — you have to spell it Self.type.

Quiz time! What do each of the permutations mean?

Self.self
self.Self
Self.Self
self.self

The number of capital letters gives you the level of meta-ness. This is
very subtle, which is probably not a good thing.

Another approach would be to introduce a new dynamictype keyword that
doesn’t need to be accessed as a member of self, and keep Self the way it
is.  Self should work in structs as a type alias.

Why don’t we turn this into a standard library function? It’s not something
you need so often that the member access is very valuable. Putting it in
the standard library as dynamicType(_:) does still allow for that function
to be implemented using compiler magic.

func dynamicType(_: T) -> T.Type { }

We have a proposal to remove .self on types. One reason .self exists is to
avoid the mistake of writing let x = Int — the compiler will give you a
weird type error later on in code if the value of x is what we today
call Int.self but you meant to call the Int() initializer. Creating a
metatype is not a common operation, so doing it explicitly is a good thing.

It’s weird that you can use the metatype directly to construct something or
to do member access, but you can’t access it as a bare value.

Coming back to this proposal, if we removed .self why would we want to
add .Self?

If you have a variable whose value is a metatype, you also keep its name in
lower case. So Self makes a little less sense from that aspect too.

Another perspective is that .dynamicType is just an implicitly synthesized
property on all type.

We do have other keywords that follow the dot on
types, Int.Type and Fooable.Protocol, so this isn’t the only thing. Those
things are magic nested types.

Subjectively, having dynamicType as a member feels weird.

If .self goes away, the four-self example above is simplified,
and .Self doesn’t make sense anymore. There’s also the difference
that .Self would be a runtime thing.


  What to do about optional requirements

http://thread.gmane.org/gmane.comp.lang.swift.evolution/14046

People commonly ask why optional only works on Objective-C protocols, and
the responses they get are usually that in Swift code you should reshape
your protocols. As a starting assumption, we’re not making optionl work in
Swift. So what do we do about this as part of the interoperability code?

People do write these, but it’s often because they’re writing a delegate
protocol and they’re following the example of Cocoa frameworks.

Roughly three things we can do:

 1. Rename it to make it clearly an Objective-C interop feature. We could
also forbid you actua

[swift-evolution] mutating/non-mutating suggestion from a Rubyist

2016-04-21 Thread Daniel Steinberg via swift-evolution
Pardon me if this has been raised before.

I gave a short presentation at our Cleveland CocoaHeads this week on what is 
coming in Swift 3. One of the attendees stayed behind to ask about the naming 
guidelines for mutating vs non-mutating. He is fairly new to Swift - coming 
from Ruby. I have no Ruby experience but am passing his thoughts on to this 
list.

He said that in Ruby they decorate the name with a symbol (I believe in their 
case it is “!”) to distinguish between the two. Although usually I’m not a fan 
of such naming conventions, we do something similar with inout parameters.

For example, if we have

func myFunc(param: inout String) { …}

we call it like this (using the Swift 3 first label convention)

myFunc(param: &aName)

We use the & to signal that the value of aName might be changed by the call to 
myFunc().

Similarly, instead of settling on a naming convention for verb vs 
verbed/verbing we could name the methods descriptively and require a symbol 
(here I use & but only for illustration) to distinguish between mutating and 
non-mutating

so we would have 

myArray.sort&()

and

sortedArray = myArray.sort()

Xcode and other tools could enforce this naming pattern and warn us that a 
mutating method must end in “&” and that a non-mutating method is not allowed 
to.

Best,

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


Re: [swift-evolution] Localization support for string interpolation

2016-04-21 Thread Uli Kusterer via swift-evolution
On 21 Apr 2016, at 16:21, Daniel Höpfl  wrote:
> I assume you want it to be part of the key? Like:
> 
>   DHLocalizedString("first: \("a"), second: \("b")")
> 
> Localizable.strings:
> 
>   "first: %1$@, second: %2$@" = "vor %2$@ kommt %1$@";
> 
> Then one would have to change 
> .
> 
> Could be done but I'm not sure if I'd like to have to include the position in 
> the key, even if there is only one argument. Could be an exception, of course.

 Yeah, idea here is principle of least surprise. Most lcoalization tools 
pre-populate the translations with the keys, so having the positional indices 
in there would mean nobody forgets it and then gets back a translation with the 
contents reversed (admittedly, since you're using the same %@ format for 
everything, at least your code won't crash. In ObjC, if someone swapped out a 
%@ and a %d, you got some "hilarious" results).

— Uli Kusterer
“The Witnesses of TeachText are everywhere..."

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


Re: [swift-evolution] [swift-dev] Lazy var and deinit

2016-04-21 Thread John McCall via swift-evolution
> On Apr 21, 2016, at 2:29 AM, Alexandr.moq via swift-dev  
> wrote:
> Should SWIFT initialize a variable in deinit method if it has not been 
> initialized? 
> 
> For example: 
> ```swift
> class A {
>   lazy var b = B()
>   deinit {
>   b.clean()
>   }
> }
> var a = A()
> a.b.doSomething() //1: variable was created
> a = A() //2: "clean" method was called for "b" variable
> a = A() //3: instance of A from step 2 should killed and "deinit" method is 
> called. In this method "b" variable will be created, "clean" will be called 
> and "b" will be killed. So, is it ok or better if swift doesn’t create lazy 
> variables in deinit if variable is not created yet
> ```
> To be honest, I don’t know which topic I should use. Because I don’t know, 
> it’s propose, bug or something else. 

It's probably a question for swift-evolution more than -dev; moving there.

The behavior you're seeing is a product of the current straightforward rule for 
what it means to access a lazy property.  I think complicating that rule to say 
something like "direct accesses in deinit produce an optional T instead of 
calling the initializer" would be... well, defensible, but a poor idea overall. 
 It would be a better language approach to allow some way to access the 
underlying optional storage of the property at any point in the program.  That 
should be easily done with the property behaviors feature when it lands, so I 
don't think we need anything else here.

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


Re: [swift-evolution] Localization support for string interpolation

2016-04-21 Thread Uli Kusterer via swift-evolution
 Daniel, thanks for posting this. As you already know from Twitter, I'm very 
much in favor of this proposal. I can pretty much not use string interpolation 
because it doesn't localize properly.

On 21 Apr 2016, at 09:42, Daniel Höpfl via swift-evolution 
 wrote:
> So, `NSLocalizedString` (and friends) would “just work” with string
> interpolation. I’m not sure about the key format to use but my proof of
> concept simply replaces every interpolation with `%@` which seems
> reasonable.

 One request: Could you perhaps use positional syntax? In some languages, the 
word order of the placeholders needs to change, and there needs to be a way to 
detect that the translator swapped two placeholders. In NSLocalizedString, that 
is done via %1$@, %2$@.

— Uli Kusterer
“The Witnesses of TeachText are everywhere..."

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


[swift-evolution] Extensions to add observers

2016-04-21 Thread Cody Weaver via swift-evolution
This is my first time posting anything in the evolution forum or the users
forum, so I apologize if this isn't how we are supposed to do things.

PROPOSAL

My idea is to add a property observer in an extension.

MOTIVATION

This would make it so we can get rid of selectors.  It's my understanding
the selectors are "Objective-C".

PROPOSED SOLUTION

   extension UIGestureRecognizer {
  self.state {
 didSet {
self.handleStateChange()
 }
  }
   }
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] [pitch] Eliminate the "T1 -> T2" syntax, require "(T1) -> T2"

2016-04-21 Thread BJ Homer via swift-evolution
How would this proposal affect curried functions? Would this:

   func foo(int: Int) -> Int -> String -> String

become this?

   func foo(int: Int) -> (((Int) -> String) -> String)

As I understand, that transformation is an accurate representation of the 
actual return type of “foo”, but it’s certainly going to raise some complaints 
among the functional Swift community if required.

-BJ




> We currently accept function type syntax without parentheses, like:
> 
> Int ->Float
> String ->()
> 
> etc. The original rationale aligned with the fact that we wanted to treat all 
> functions as taking a single parameter (which was often of tuple type) and 
> producing a tuple value (which was sometimes a tuple, in the case of void and 
> multiple return values). However, we’ve long since moved on from that early 
> design point: there are a number of things that you can only do in a 
> parameter list now (varargs, default args, etc), implicit tuple splat has 
> been removed, and the compiler has long ago stopped modeling function 
> parameters this way. Beyond that, it eliminates one potential style war.
> 
> Given all this, I think it makes sense to go for syntactic uniformity between 
> parameter list and function types, and just require parenthesis on the 
> argument list. The types above can be trivially written as:
> 
> (Int) ->Float
> (String) ->()
> 
> Thoughts?
> 
> -Chris
> 
> 
> 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Notes from Swift core team 2016-04-20 design discussion

2016-04-21 Thread Alex Martini via swift-evolution
To help keep proposals moving forward, the Swift core team has set aside some 
time specifically for design discussions of upcoming proposals.  Below are some 
rough notes from the yesterday's discussion.

These are informal comments, intended to guide the proposals in directions that 
draw constructive feedback. You are welcome to ignore the feedback, agree with 
it, or disagree with it.  As always, the formal decision doesn't happen until 
after the review period ends.

SE-0068: Expanding Swift Self to class members and value types 

https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
 

We have one keyword left in the language, dynamicType, which is camel cased. 
This proposal renames it to Self instead.

In a static function today, self.dynamicType will give you a metatype but the 
non-member Self will not. The most useful reason to reference it is to call an 
initializer. It makes accessing the metatype weirder. It’s not Self.Type; 
that’s a type — you have to spell it Self.type.

Quiz time! What do each of the permutations mean?

Self.self
self.Self
Self.Self
self.self
The number of capital letters gives you the level of meta-ness. This is very 
subtle, which is probably not a good thing.

Another approach would be to introduce a new dynamictype keyword that doesn’t 
need to be accessed as a member of self, and keep Self the way it is.  Self 
should work in structs as a type alias.

Why don’t we turn this into a standard library function? It’s not something you 
need so often that the member access is very valuable. Putting it in the 
standard library as dynamicType(_:) does still allow for that function to be 
implemented using compiler magic.

func dynamicType(_: T) -> T.Type { }
We have a proposal to remove .self on types. One reason .self exists is to 
avoid the mistake of writing let x = Int — the compiler will give you a weird 
type error later on in code if the value of x is what we today call Int.self 
but you meant to call the Int() initializer. Creating a metatype is not a 
common operation, so doing it explicitly is a good thing.

It’s weird that you can use the metatype directly to construct something or to 
do member access, but you can’t access it as a bare value.

Coming back to this proposal, if we removed .self why would we want to add 
.Self?

If you have a variable whose value is a metatype, you also keep its name in 
lower case. So Self makes a little less sense from that aspect too.

Another perspective is that .dynamicType is just an implicitly synthesized 
property on all type.

We do have other keywords that follow the dot on types, Int.Type and 
Fooable.Protocol, so this isn’t the only thing. Those things are magic nested 
types.

Subjectively, having dynamicType as a member feels weird.

If .self goes away, the four-self example above is simplified, and .Self 
doesn’t make sense anymore. There’s also the difference that .Self would be a 
runtime thing.

What to do about optional requirements 

http://thread.gmane.org/gmane.comp.lang.swift.evolution/14046 

People commonly ask why optional only works on Objective-C protocols, and the 
responses they get are usually that in Swift code you should reshape your 
protocols. As a starting assumption, we’re not making optionl work in Swift. So 
what do we do about this as part of the interoperability code?

People do write these, but it’s often because they’re writing a delegate 
protocol and they’re following the example of Cocoa frameworks.

Roughly three things we can do:

Rename it to make it clearly an Objective-C interop feature. We could also 
forbid you actually spelling it in Swift code. That doesn’t work well because 
it breaks your ability to write code in Swift that has Objective-C clients — 
those clients won’t get the default implementation from the extensions like you 
would use with Swift clients instead of creating optional requirements.
Modeling optional requirements as a function of optional type such as ((A, B) 
-> C)? doesn’t work well. For example, properties can have optional type and 
they can be optional requirements, so you would end up having to deal with a 
lot of extra complexity due to double-optionals and likely want better code 
completion so you could type it all out.
You force the default implementation to be visible from all callers, and you do 
the dispatch at the call site. The only advantage of this is that it takes 
optional requirements out of the language entirely. If you wanted to implement 
the (somewhat common) pattern of checking whether a type implements an optional 
requirement, you would have to use a respondsToSelector check.
The best pattern we’ve seen for checking conformance and using different code 
paths based on that is to use finer-grained protocols. (But there are still 
issues with organizing yo

Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread Wallacy via swift-evolution
FWIW:

Im working on a proposal to cover this points, using protocols a few days.
One or two days i will post...

Em qui, 21 de abr de 2016 09:27, Tal Atlas via swift-evolution <
swift-evolution@swift.org> escreveu:

> I agree that the solution to any of these problems would be better done
> with improvements to protocol extensions. Having multiple tools to get the
> same trick done doesn’t seem worth it in this case.
>
> -Tal
>
> On Thu, Apr 21, 2016 at 7:00 AM, James Froggatt via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> I sometimes find myself wanting to use private protocols + extensions to
>> try to add public functions to a set of types. Something like this:
>>
>> private protocol ArrayBackedType {
>> var data: [String] {get set}
>> }
>> public extension ArrayBackedType: UITableViewDataSource {
>> /*standard table view methods here*/
>> }
>>
>> This would currently require two changes to the language: public
>> extensions to private protocols, and support for ObjC-compatible functions
>> in extensions (which should be possible for private/internal protocols).
>>
>> Additionally, extensions could get the ability to add storage to the
>> (non-imported) type they extend, so:
>>
>> internal protocol ArrayBackedType {}
>> public extension ArrayBackedType: UITableViewDataSource {
>> private var data: [String] = []
>> dynamic func tableView(…)
>> }
>>
>> The separate protocol & extension declarations could then get some
>> syntactic sugar:
>>
>> /*can't be public, since it can add properties, internal availability
>> matches that of the protocol in the previous example*/
>> internal protocol extension ArrayBackedType { … }
>>
>> or even more concisely:
>> internal trait ArrayBackedType { … }
>>
>> Could traits be constructed from protocol extensions in this way, or
>> otherwise end up competing with them if just some of these features were to
>> be added? My concern is that adding traits as a separate language feature
>> could put them in direct competition with protocol extensions.
>>
>>  Begin Message 
>> Group: gmane.comp.lang.swift.evolution
>> MsgID: <
>> caebsastvgd6nezdnfhtmwvwunc7ebdqatjajhzfn4voxdvp...@mail.gmail.com>
>>
>> Another traits implemenation
>>
>> http://php.net/manual/en/language.oop5.traits.php
>> On Apr 21, 2016 5:53 PM, "Niall Young via swift-evolution" <
>> swift-evolution-m3fhrko0vlzytjvyw6y...@public.gmane.org> wrote:
>>
>> >At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:
>> >
>> >I feel like the solution to the Arrow/Enemy problem that best fits with
>> >>Swift's current available tools is neither a protocol (which, as you
>> >>mentioned, doesn't get rid of the initialization/configuration of the
>> >>member data) or inheritance (which, as you mentioned, can only have one
>> >>base type) -- it's to extract a third type that handles
>> >>
>> >
>> >What you're describing sounds _exactly_ like Traits :-)
>> >
>> >http://scg.unibe.ch/research/traits
>> >
>> >Traits could be a peer of extensions, filling a niche that isn't quite
>> the
>> >same niche as a default implementation, but it could be consistently and
>> >safely consumed like an extension, with its own rules of consumption
>> >(flattening) - to implement any need or explicit protocol requirement
>> that
>> >a Class, Value Type or Protocol has at compile-time.
>> >
>> >Think of a Trait as providing a consumable set of functions.  Now imagine
>> >that we're combining the collective declarations of 1..N Traits all
>> >together, consumed by a Class or Value Type (or Protocol!) in a
>> predicable
>> >and safe way (flattening: see the first Traits white paper).
>> >
>> >i.e. we get the same result regardless of the order of consumption, how
>> >many times any given Trait(s) were consumed, Traits dependent on other
>> >Traits etc.  Predictable results, given the same input we always get the
>> >same output.  This is flattening, but read the white papers for more
>> detail.
>> >
>> >The process of flattening itself could be a peer of the existing rules
>> >around static dispatch vs. dynamic dispatch around
>> >default-implementations/extensions vs. class overrides.
>> >
>> >A Trait declaration could look something ~like:
>> >
>> >trait TraitX (ProtocolAdherenceY): DependentTrait1,
>> >DependentTrait2 {
>> >
>> >private var foo
>> >private let bah { .. }
>> >
>> >func fooify { .. }
>> >mutating func bahify { .. }
>> >private func hah { .. }
>> >
>> >}
>> >
>> >with a Trait being a closure, where _only private_ data Properties can be
>> >declared, providing 1..N function implementations.  It could conform
>> >_towards_ a Protocol (partial to full conformance), and also be dependent
>> >upon other names Traits, which would be consumed in parallel as a
>> >first-class citizen with the Trait that depends on it.
>> >
>> >Traits could be consumed by a class or value type, to provide function
>> >implementations which could be satisfying a Protocol implementation

Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread David Waite via swift-evolution

> On Apr 21, 2016, at 3:52 AM, Niall Young via swift-evolution 
>  wrote:
> 
> At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:
> 
>> I feel like the solution to the Arrow/Enemy problem that best fits with
>> Swift's current available tools is neither a protocol (which, as you
>> mentioned, doesn't get rid of the initialization/configuration of the
>> member data) or inheritance (which, as you mentioned, can only have one
>> base type) -- it's to extract a third type that handles
> 
> What you're describing sounds _exactly_ like Traits :-)
> 
>   http://scg.unibe.ch/research/traits
> 
> Traits could be a peer of extensions, filling a niche that isn't quite the 
> same niche as a default implementation, but it could be consistently and 
> safely consumed like an extension, with its own rules of consumption 
> (flattening) - to implement any need or explicit protocol requirement that a 
> Class, Value Type or Protocol has at compile-time.
> 
> Think of a Trait as providing a consumable set of functions.  Now imagine 
> that we're combining the collective declarations of 1..N Traits all together, 
> consumed by a Class or Value Type (or Protocol!) in a predicable and safe way 
> (flattening: see the first Traits white paper).

extensions give us something trait-like, but with only one, non-opt-in 
implementation and usually per protocol. I’d imagine a true trait system to 
allow for more specific default implementations of Sequence, for example.

> i.e. we get the same result regardless of the order of consumption, how many 
> times any given Trait(s) were consumed, Traits dependent on other Traits etc. 
>  Predictable results, given the same input we always get the same output.  
> This is flattening, but read the white papers for more detail.
> 
> The process of flattening itself could be a peer of the existing rules around 
> static dispatch vs. dynamic dispatch around 
> default-implementations/extensions vs. class overrides.
> 
> A Trait declaration could look something ~like:
> 
>   trait TraitX (ProtocolAdherenceY): DependentTrait1, DependentTrait2 {
> 
>   private var foo
>   private let bah { .. }
> 
>   func fooify { .. }
>   mutating func bahify { .. }
>   private func hah { .. }
> 
>   }
> 
> with a Trait being a closure, where _only private_ data Properties can be 
> declared, providing 1..N function implementations.  It could conform 
> _towards_ a Protocol (partial to full conformance), and also be dependent 
> upon other names Traits, which would be consumed in parallel as a first-class 
> citizen with the Trait that depends on it.

Traits typically cannot declare fields/state. Is this not where you start to 
cross over to Mixins?

I attempted to model this (today) via delegates for behavioral dependencies on 
traits and self-wiring, but this creates issues with value type copying and 
circular references in reference types. For that reason, I didn’t feel it was 
appropriate to make a formal trait proposal until more definition toward 
behaviors (e.g. Joe Groff’s property behaviors) or macros were in the 
discussion.


> Stateful Traits suggest that as long as the data is private _to the Trait_ 
> then we can safely ignore some of the complexity of state in Traits - it just 
> isn't exposed as the Trait declaration itself is a closure.  Dependency on 
> state in the consumer could proxy to class/instance/value-type data via 
> Protocol.

Yes, but this means that said data may be duplicated and need to be kept in 
sync between traits and the main type. It also means that traits cannot be used 
while extending an existing type to meet new protocol requirements outside a 
module, as that may change the size of the type itself to be different than 
what precompiled code expects.

-DW

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


Re: [swift-evolution] [SR-933] Rename flatten to flattened

2016-04-21 Thread David Waite via swift-evolution

> On Apr 21, 2016, at 1:08 AM, Vladimir.S via swift-evolution 
>  wrote:
>> 
> 
> Is it "SE-0006" ?
> https://github.com/apple/swift-evolution/blob/master/proposals/0006-apply-api-guidelines-to-the-standard-library.md
>  
> 
> 
> Could you please point me to lines in this document where it says that 
> "map/filter/reduce" are exceptions and we don't need to rename them to 
> mapped/filtered/reduced ? Thank you.
> 
https://swift.org/documentation/api-design-guidelines/#use-terminology-well 
 , 
see "Stick to the established meaning” and “Embrace precedent"

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


Re: [swift-evolution] Localization support for string interpolation

2016-04-21 Thread Daniel Höpfl via swift-evolution

On 2016-04-21 12:41, Uli Kusterer wrote:

[...]
 One request: Could you perhaps use positional syntax? In some
languages, the word order of the placeholders needs to change, and
there needs to be a way to detect that the translator swapped two
placeholders. In NSLocalizedString, that is done via %1$@, %2$@.


Using it in the translated string already works (see test cases).

I assume you want it to be part of the key? Like:

   DHLocalizedString("first: \("a"), second: \("b")")

Localizable.strings:

   "first: %1$@, second: %2$@" = "vor %2$@ kommt %1$@";

Then one would have to change 
.


Could be done but I'm not sure if I'd like to have to include the 
position in the key, even if there is only one argument. Could be an 
exception, of course.


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


Re: [swift-evolution] [Review] SE-0068: Expanding Swift Self to class members and value types

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

> On Apr 21, 2016, at 5:53 AM, Jeremy Pereira via swift-evolution 
>  wrote:
> 
> 
>> On 21 Apr 2016, at 02:14, Brent Royal-Gordon via swift-evolution 
>>  wrote:
>> 
>>> 1) “Self" differs from “self” by just the first letter being capitalized. 
>>> Regardless of case, it is confusing for the terms “self” or “Self” or 
>>> “SELF” to mean different things from within the same context.
>> 
>> What, you've never done things like this?
>> 
>> let page = Page()
>> let document = Document(pages: [page])
>> 
>> let account = Account(oAuthToken: token)
>> account.addDocument(document)
> 
> I have, but I always feel a tinge of guilt when I do it. I know I shouldn’t.
> 
> Fortunately, karma is satisfied because Xcode autocomplete punishes me by 
> always putting the capitalised version as the top choice.

Capitalized Self already exists in the language. This proposal extends the use 
to add consistency. Would you prefer to remove it entirely?

For example: 
http://stackoverflow.com/questions/27863810/swift-difference-between-self-and-self

-- E

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


Re: [swift-evolution] [Idea] Passing an Array to Variadic Functions

2016-04-21 Thread Patrick Smith via swift-evolution
Is there some way that (Type...) as an argument could become to mean ‘Any 
Collection of type’? A short hand for generic C : CollectionType where 
C.Generator.Element == Type.
  // Function accepting any collection of Int  func sum(numbers: Int...) { 
numbers.reduce(0, combine: +)    // Accepts all of the following:  func(5, 6, 
7)  func([5, 6, 7])  func(1...100)  func(1...100.lazy.filter{ $0 % 2 == 0 })
It’s just a shame that generic collections are so handy, but a pain to write, 
whereas parameters of array just need [Type]. Not sure if this could be grafted 
on top, but just a thought. Possibly any sequence would be even better.
(The only situation it would be disabled is for a type of Any)

Patrick




On Thu, Apr 21, 2016 at 6:12 AM -0700, "Jeremy Pereira via swift-evolution" 
 wrote:











> On 20 Apr 2016, at 15:56, Tino Heth <2...@gmx.de> wrote:
> 
> 
>> The question is whether the downside to variadic parameters is really enough 
>> to justify _removing_ an existing language feature. 
>> 
>> The burden of justification should be on those people wanting to change the 
>> language, not on those wanting to maintain the status quo and “I don’t like 
>> it” or “I think it makes code a tiny bit less readable” is not sufficient 
>> justification, in my opinion because you already have the option not to use 
>> the feature. 
> Afaics, this isn't true:
> Increment/decrement operators, currying, tuple splat and even the C-style for 
> loop have already been deprecated, and although I would have preferred to 
> keep some of those constructs, I think it is good how progressive Swift is 
> pushed forward ("would we add this feature now if it wasn't already there?”).

How do these examples show that the burden of justification should not be on 
those people making the change? I have not claimed that language features 
should never be removed, only that removal needs some sort of real 
justification.

I don’t think "would we add this feature now if it wasn't already there?” is 
sufficient anymore, if it ever was. The global Swift code base is growing day 
by day and each time you remove a feature, you piss somebody off. If the 
perception of the Swift community is that we keep taking their toys away, it 
will impede the growth in Swift’s popularity.

> 
> The value of variadic functions is imho less than the possibility to omit 
> "()" in procedure calls, and afair, there have been several posts that 
> illustrate the complications of this feature.


I don’t think “it’s a bit complicated” is necessarily good justification for 
removing a feature. 
___
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] Localization support for string interpolation

2016-04-21 Thread Daniel Höpfl via swift-evolution

Sorry, I don't see the problem.

< and > are considered normal characters, that's fine.

The trick of DHLocalizedString is that it does not do the string 
interpolation. This is already handled by Swift.


If you call DHLocalizedString("<\(quote)> by <\(person)>"), the compiler 
generates something like:


DHLocalizedString(DHLocalizedStringStore("<",
 quote.description(),
 "> by <",
 person.description(),
 ">"),
  tableName = nil,
  bundle = nil)

DHLocalizedString concats the strings (stored in the 
DHLocalizedStringStore), replacing every even position by "%@". The 
resulting string is used as format argument of NSLocalizedString, using 
the even positions of the array as arguments. DHLocalizedString does not 
care about the contents of any of the strings parts.


All of this works because Swift always starts interpolated strings with 
a string literal, "\(4)" becomes ["", "4", ""] (not sure if it adds the 
empty string at the end, too). The parts that come from interpolation 
are always in the even positions.


My proposal has two parts:

a) Make NSLocalizedString work like DHLocalizedString does.
b) Make `xxx` a synonym to NSLocalizedString("xxx") (and give me a way 
to set the default values for tableName/bundle in this case)


On 2016-04-21 12:23, Adrian Zubarev via swift-evolution wrote:

I know that :D I mean < and > are considered as normal characters of
the string "<\(quote)> by <\(person)>“ so thats why this won’t
work that way.

--
Adrian Zubarev
Am 21. April 2016 bei 11:32:05, Daniel Höpfl via swift-evolution
(swift-evolution@swift.org) schrieb:


Maybe using "<\(quote)> by <\(person)>"


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

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


Re: [swift-evolution] [Idea] Passing an Array to Variadic Functions

2016-04-21 Thread Jeremy Pereira via swift-evolution

> On 20 Apr 2016, at 19:24, Dave Abrahams via swift-evolution 
>  wrote:
> 
> 
> on Wed Apr 20 2016, Tino Heth  wrote:
> 
>> Increment/decrement operators, currying, tuple splat and even the
>> C-style for loop have already been deprecated, and although I would
>> have preferred to keep some of those constructs, I think it is good
>> how progressive Swift is pushed forward ("would we add this feature
>> now if it wasn't already there?").
> 
> We're in a stage of Swift's development where we can ask this question
> fairly freely,

I think we are already past that stage, whether we like it or not. There is 
already quite a lot of Swift code in “production” and some people in the wider 
community are already resenting some of the removals.


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


Re: [swift-evolution] [Idea] Passing an Array to Variadic Functions

2016-04-21 Thread Jeremy Pereira via swift-evolution

> On 20 Apr 2016, at 15:56, Tino Heth <2...@gmx.de> wrote:
> 
> 
>> The question is whether the downside to variadic parameters is really enough 
>> to justify _removing_ an existing language feature. 
>> 
>> The burden of justification should be on those people wanting to change the 
>> language, not on those wanting to maintain the status quo and “I don’t like 
>> it” or “I think it makes code a tiny bit less readable” is not sufficient 
>> justification, in my opinion because you already have the option not to use 
>> the feature. 
> Afaics, this isn't true:
> Increment/decrement operators, currying, tuple splat and even the C-style for 
> loop have already been deprecated, and although I would have preferred to 
> keep some of those constructs, I think it is good how progressive Swift is 
> pushed forward ("would we add this feature now if it wasn't already there?”).

How do these examples show that the burden of justification should not be on 
those people making the change? I have not claimed that language features 
should never be removed, only that removal needs some sort of real 
justification.

I don’t think "would we add this feature now if it wasn't already there?” is 
sufficient anymore, if it ever was. The global Swift code base is growing day 
by day and each time you remove a feature, you piss somebody off. If the 
perception of the Swift community is that we keep taking their toys away, it 
will impede the growth in Swift’s popularity.

> 
> The value of variadic functions is imho less than the possibility to omit 
> "()" in procedure calls, and afair, there have been several posts that 
> illustrate the complications of this feature.


I don’t think “it’s a bit complicated” is necessarily good justification for 
removing a feature. 
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Lazy var and deinit

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

Seems to solve this problem I can suggest only this ugly solution:

class A {
lazy var _b = B()
var _b_used = false

var b : B {
get {_b_used = true; return _b }
set {_b_used = true; _b = newValue }
}

deinit {
print("deinit A")

if _b_used {
b.clean()
}
}

}

Better solution?

On 21.04.2016 13:27, Alexandr.moq via swift-evolution wrote:

Should SWIFT initialize a variable in deinit method if it has not been 
initialized?

For example:
```swift
class A {
lazy var b = B()
deinit {
b.clean()
}
}
var a = A()
a.b.doSomething() //1: variable was created
a = A() //2: "clean" method was called for "b" variable
a = A() //3: instance of A from step 2 should killed and "deinit" method is called. In this method 
"b" variable will be created, "clean" will be called and "b" will be killed. So, is it ok 
or better if swift doesn’t create lazy variables in deinit if variable is not created yet
```
To be honest, I don’t know which topic I should use. Because I don’t know, it’s 
propose, bug or something else.
___
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 draft] Enhanced floating-point protocols

2016-04-21 Thread Thorsten Seitz via swift-evolution
I totally agree with Dave Sweeris. He has put the issue quite nicely.

Being able to add protocol conformance to a protocol would indeed solve this 
problem (having well designed protocols in the standard library would still be 
nice, though, so many thanks for the pointers, Dave A, that looks really 
interesting!).

-Thorsten

> Am 20.04.2016 um 23:23 schrieb Dave via swift-evolution 
> :
> 
> 
>> On Apr 20, 2016, at 1:15 PM, Dave Abrahams via swift-evolution 
>>  wrote:
>> 
>> 
>> on Tue Apr 19 2016, Thorsten Seitz  wrote:
>> 
>>> I'd like to have something like Summable with 'add', 'adding' and 'zero' 
>>> being a
>>> separate protocol as well as somthing like Multiplicative with 'multiply',
>>> 'multiplied' and 'one' being a separate protocol, because these are 
>>> universally
>>> interesting for other cases, e.g. Summable would be useful for defining path
>>> lengths in a graph library.
>>> 
>>> Would you mind adding that to the proposal?
>> 
>> I suspect you may be headed into the realm of
>> protocols-as-bags-of-syntax.
> You say that like it’s a bad thing… Am I missing the point? (NOT a rhetorical 
> question)
> 
> Speaking only for myself, I want stuff broken up into many simpler protocols 
> (which `Arithmetic` and such conform to) because there are many algorithms 
> which only require small parts of the larger protocol. What if I wanted to 
> add a function that sums all the elements in a collection?
> extension CollectionType where Generator.Element: Arithmetic {
> func sum() -> Generator.Element {
> var s = Generator.Element()
> for e in self {
> s.add(e)
> }
> return s
> }
> }
> 
> Yeah, it works, but if I want to get the sum of a collection of some custom 
> type, I have to implement *all* of `Arithmetic`, as opposed to just the two 
> parts of it (`init()` and `.add(:)`) that the algorithm actually uses. It’d 
> be both simpler for the users and *more to the point of the function*, if it 
> could be written like this:
> extension CollectionType where Generator.Element: Addable { // "Addable" 
> instead of "Arithmetic"
> ... // No change here
> }
> 
> Now, if Swift allowed you to add protocol conformance to protocols:
> protocol Addable {
> ... // Relevant subset of `Arithmetic`
> }
> #for T in Arithmetic { // "#for" because this is clearly macro-ish, and # 
> seems to be what we've settled on for that
> extension T : Addable {} // Don't need anything here since `Arithmetic` 
> already has everything in `Addable`
> }
> … then this all becomes a somewhat moot point. If some generic function only 
> needs a subset of a protocol’s functionality, said function’s author could do 
> this “#for T …” song & dance, and their function would be defined with the 
> minimum constraints.
> 
> 
>> Look at pages 14 and 24 of
>> —which does the job
>> right for C++—and you'll see why.
> COOL!!! Thanks for posting that, it looks like it’ll be a great read! :-D
> 
> - Dave Sweeris
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Idea] Passing an Array to Variadic Functions

2016-04-21 Thread Jeremy Pereira via swift-evolution

> On 20 Apr 2016, at 13:10, Haravikk  wrote:
> 
> 
>> On 20 Apr 2016, at 11:44, Jeremy Pereira  
>> wrote:
>>> Pros:
>>> • Slightly cleaner syntax at call-site.
>>> • Possibly optimisations unavailable to Array passing?
>> 
>> • Makes calling C and Objective-C functions with variadic parameters less 
>> confusing
>> • Will not break existing Swift code that uses variadic parameters
> 
> In both cases you just have to add square brackets to make it an array 
> instead, which doesn’t seem more confusing to me since that’s actually what 
> you’re doing anyway.

But you still have to do it and a call to (say) printf would look different to 
its C declaration. Each individual change may not be onerous but you advocating 
something that will cause an annoyance to a lot of people for a highly 
subjective gain.

> 
>> • Makes generalising some functions cleaner e.g. zip(a, b) could be 
>> generalised to any number of parameters as already mentioned, but if you 
>> instead used an array, we would end up with a massive thread about whether 
>> the original two parameter zip should be removed
> 
> Only if the two-parameter form isn’t implemented any differently;

Why would it be implemented differently?

>> My quick an uscientific survey of questions and answers relating to variadic 
>> parameters on StackOverflow yields no instances of people asking what does 
>> the`…` in `func foo(a: Int…)` do which suggests that the learning curve is 
>> actually fairly trivial. However their is a megaton of questions asking 
>> things like “why can’t I pass an array" and "how do I forward variadic 
>> arguments to another variadic function”.
> 
> The ellipsis syntax is straightforward enough, but I think the problem lies 
> more with variadics that overload similar function signatures (like the zip() 
> method) where it becomes less clear what you’re calling, and what’s happening 
> in that call (even if the actual method is pretty much the same). Passing 
> arguments on also couldn’t be simpler in the array form, as you simply pass 
> the array into another function that can take one.

I’m not against the idea of an addition to the language that would create a 
mechanism to allow passing arrays to variadic functions. I’m simply against the 
idea of removing the existing feature. As far as I can see, the only arguments 
put forward are “it might be confusing” and “I don’t like it". I think the bar 
should be higher than that
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0068: Expanding Swift Self to class members and value types

2016-04-21 Thread Jeremy Pereira via swift-evolution

> On 20 Apr 2016, at 18:16, Chris Lattner via swift-evolution 
>  wrote:
> 
> 
>   * What is your evaluation of the proposal?

-1

Addressing the issues cited in the proposal:

>   • dynamicType remains an exception to Swift's lowercased keywords rule. 
> This change eliminates a special case that's out of step with Swift's new 
> standards.


Except for the fact that `dynamicType` cannot be used with implicit self, it 
has always felt more like a property to me than a keyword and the 
capitalisation is therefore not out of place. The camel case does not jar for 
me in the same way that writing `someInstance.Self` would.

NB the keyword `Self` would also violate the all-lowercase keyword rule.

>   • Self is shorter and clearer in its intent. It mirrors self, which 
> refers to the current instance.

It is undeniably shorter, but it is not clearer in intent. `self.dynamicType` 
clearly and explicitly tells us we are referring to the runtime type of the 
instance. `Self` does not. Furthermore, it overloads the word with two subtly 
different meanings depending on context. 

>   • It provides an easier way to access static members. As type names 
> grow large, readability suffers. MyExtremelyLargeTypeName.staticMember is 
> unwieldy to type and read.

I reject the assertion that readability suffers with large type names. 
`NSApplicationDelegate` is much more readable than `NSAppDlgt` for example.

Furthermore, this proposal does not address the length of 
`MyExtremelyLargeTypeName.someMember()` since that might not be the same method 
as `Self.someMember()` If you explicitly want the `someMember()` defined by 
`MyExtremelyLargeTypeName` you still have to spell it out in case it is a class 
function and the dynamic type is a subclass.  

>   • Code using hardwired type names is less portable than code that 
> automatically knows its type.

And how does `self.dynamicType` fail here?

>   • Renaming a type means updating any TypeName references in code.

This is the same point as the previous one.

>   • Using self.dynamicType fights against Swift's goals of concision and 
> clarity in that it is both noisy and esoteric.

I disagree. `self.dynamicType` is a clear and concise description of the object 
it represents.

Another observation: the proposal omits the “Impact own Existing Code” section. 
I think this would be a breaking change for a lot of existing code.

Also, I’m disappointed that no alternatives seem to have been documented.


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

No.

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

No, unless the direction of Swift is to go for maximum terseness at the expense 
of clarity.

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

In Objective-C you can write [self class] to get the runtime class of an 
object. I think that is a better choice of name. In Swift the analogue would 
probably be `self.type`. Was this considered?


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

I’ve been following the thread.


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


Re: [swift-evolution] [Review] SE-0068: Expanding Swift Self to class members and value types

2016-04-21 Thread Tal Atlas via swift-evolution
I’m totally fine with the case difference and overall like the change. I’m
just not sure if this just an alias for `self.dynamicType` that it’s worth
that sugar at this point.

-Tal

On Thu, Apr 21, 2016 at 8:16 AM, Pelaia II, Tom via swift-evolution <
swift-evolution@swift.org> wrote:

> I regularly work with Linux and am quite comfortable with case sensitive
> file systems, but I wouldn’t ever use the same name differing only in case
> in the same directory. To me, file names or variable names should be
> meaningful independent of case. Of course, with the language we have the
> convention on using cases that imply what something is. That is a good
> thing. For me, the case is used more often to add clarity of meaning than
> to resolve different entities with the same name except for case. Using
> “Self” and “self” is certainly consistent with the language rules and
> naming convention, but not something I think should be encouraged.
>
>
> On Apr 21, 2016, at 1:10 AM, L Mihalkovic 
> wrote:
>
> I couldn't understand for a moment why people would think that “Self"
> versus "self” is confusing.. and then I remembered that Apple does not (by
> default) distinguish file names with different casing in the filesystem… I
> think we either educate people or we keep them ignorant in the name of
> their best interest. Apple seem to regularly choose the bottom end. I hope
> after 40 years someone will decide it is time to look forward and embrace
> Self
>
> On Apr 21, 2016, at 3:14 AM, Brent Royal-Gordon via swift-evolution <
> swift-evolution@swift.org> wrote:
>
> 1) “Self" differs from “self” by just the first letter being capitalized.
> Regardless of case, it is confusing for the terms “self” or “Self” or
> “SELF” to mean different things from within the same context.
>
>
> What, you've never done things like this?
>
> let page = Page()
> let document = Document(pages: [page])
>
> let account = Account(oAuthToken: token)
> account.addDocument(document)
>
> --
> Brent Royal-Gordon
> Sent from my iPhone
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
>
> ___
> swift-evolution mailing list
> swift-evolution@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread Tal Atlas via swift-evolution
I agree that the solution to any of these problems would be better done
with improvements to protocol extensions. Having multiple tools to get the
same trick done doesn’t seem worth it in this case.

-Tal

On Thu, Apr 21, 2016 at 7:00 AM, James Froggatt via swift-evolution <
swift-evolution@swift.org> wrote:

> I sometimes find myself wanting to use private protocols + extensions to
> try to add public functions to a set of types. Something like this:
>
> private protocol ArrayBackedType {
> var data: [String] {get set}
> }
> public extension ArrayBackedType: UITableViewDataSource {
> /*standard table view methods here*/
> }
>
> This would currently require two changes to the language: public
> extensions to private protocols, and support for ObjC-compatible functions
> in extensions (which should be possible for private/internal protocols).
>
> Additionally, extensions could get the ability to add storage to the
> (non-imported) type they extend, so:
>
> internal protocol ArrayBackedType {}
> public extension ArrayBackedType: UITableViewDataSource {
> private var data: [String] = []
> dynamic func tableView(…)
> }
>
> The separate protocol & extension declarations could then get some
> syntactic sugar:
>
> /*can't be public, since it can add properties, internal availability
> matches that of the protocol in the previous example*/
> internal protocol extension ArrayBackedType { … }
>
> or even more concisely:
> internal trait ArrayBackedType { … }
>
> Could traits be constructed from protocol extensions in this way, or
> otherwise end up competing with them if just some of these features were to
> be added? My concern is that adding traits as a separate language feature
> could put them in direct competition with protocol extensions.
>
>  Begin Message 
> Group: gmane.comp.lang.swift.evolution
> MsgID:  >
>
> Another traits implemenation
>
> http://php.net/manual/en/language.oop5.traits.php
> On Apr 21, 2016 5:53 PM, "Niall Young via swift-evolution" <
> swift-evolution-m3fhrko0vlzytjvyw6y...@public.gmane.org> wrote:
>
> >At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:
> >
> >I feel like the solution to the Arrow/Enemy problem that best fits with
> >>Swift's current available tools is neither a protocol (which, as you
> >>mentioned, doesn't get rid of the initialization/configuration of the
> >>member data) or inheritance (which, as you mentioned, can only have one
> >>base type) -- it's to extract a third type that handles
> >>
> >
> >What you're describing sounds _exactly_ like Traits :-)
> >
> >http://scg.unibe.ch/research/traits
> >
> >Traits could be a peer of extensions, filling a niche that isn't quite the
> >same niche as a default implementation, but it could be consistently and
> >safely consumed like an extension, with its own rules of consumption
> >(flattening) - to implement any need or explicit protocol requirement that
> >a Class, Value Type or Protocol has at compile-time.
> >
> >Think of a Trait as providing a consumable set of functions.  Now imagine
> >that we're combining the collective declarations of 1..N Traits all
> >together, consumed by a Class or Value Type (or Protocol!) in a predicable
> >and safe way (flattening: see the first Traits white paper).
> >
> >i.e. we get the same result regardless of the order of consumption, how
> >many times any given Trait(s) were consumed, Traits dependent on other
> >Traits etc.  Predictable results, given the same input we always get the
> >same output.  This is flattening, but read the white papers for more
> detail.
> >
> >The process of flattening itself could be a peer of the existing rules
> >around static dispatch vs. dynamic dispatch around
> >default-implementations/extensions vs. class overrides.
> >
> >A Trait declaration could look something ~like:
> >
> >trait TraitX (ProtocolAdherenceY): DependentTrait1,
> >DependentTrait2 {
> >
> >private var foo
> >private let bah { .. }
> >
> >func fooify { .. }
> >mutating func bahify { .. }
> >private func hah { .. }
> >
> >}
> >
> >with a Trait being a closure, where _only private_ data Properties can be
> >declared, providing 1..N function implementations.  It could conform
> >_towards_ a Protocol (partial to full conformance), and also be dependent
> >upon other names Traits, which would be consumed in parallel as a
> >first-class citizen with the Trait that depends on it.
> >
> >Traits could be consumed by a class or value type, to provide function
> >implementations which could be satisfying a Protocol implementation
> >requirement, along with its own private functions and private data for its
> >(private to Trait) local state etc.  The consumption syntax I'm still
> >unsure of, but a clear declarative "flattens Trait1, Trait2, .. , TraitN"
> >or similar would do.
> >
> >The consuming Class or Value Type would remain fully responsible for its
> >own Protocol conformance, and if any of the consumed Trait public
> >implementat

Re: [swift-evolution] [Review] SE-0068: Expanding Swift Self to class members and value types

2016-04-21 Thread Pelaia II, Tom via swift-evolution
I regularly work with Linux and am quite comfortable with case sensitive file 
systems, but I wouldn’t ever use the same name differing only in case in the 
same directory. To me, file names or variable names should be meaningful 
independent of case. Of course, with the language we have the convention on 
using cases that imply what something is. That is a good thing. For me, the 
case is used more often to add clarity of meaning than to resolve different 
entities with the same name except for case. Using “Self” and “self” is 
certainly consistent with the language rules and naming convention, but not 
something I think should be encouraged.


On Apr 21, 2016, at 1:10 AM, L Mihalkovic 
mailto:laurent.mihalko...@gmail.com>> wrote:

I couldn't understand for a moment why people would think that “Self" versus 
"self” is confusing.. and then I remembered that Apple does not (by default) 
distinguish file names with different casing in the filesystem… I think we 
either educate people or we keep them ignorant in the name of their best 
interest. Apple seem to regularly choose the bottom end. I hope after 40 years 
someone will decide it is time to look forward and embrace Self

On Apr 21, 2016, at 3:14 AM, Brent Royal-Gordon via swift-evolution 
mailto:swift-evolution@swift.org>> wrote:

1) “Self" differs from “self” by just the first letter being capitalized. 
Regardless of case, it is confusing for the terms “self” or “Self” or “SELF” to 
mean different things from within the same context.

What, you've never done things like this?

let page = Page()
let document = Document(pages: [page])

let account = Account(oAuthToken: token)
account.addDocument(document)

--
Brent Royal-Gordon
Sent from my iPhone

___
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-0068: Expanding Swift Self to class members and value types

2016-04-21 Thread Jeremy Pereira via swift-evolution

> On 21 Apr 2016, at 02:14, Brent Royal-Gordon via swift-evolution 
>  wrote:
> 
>> 1) “Self" differs from “self” by just the first letter being capitalized. 
>> Regardless of case, it is confusing for the terms “self” or “Self” or “SELF” 
>> to mean different things from within the same context.
> 
> What, you've never done things like this?
> 
> let page = Page()
> let document = Document(pages: [page])
> 
> let account = Account(oAuthToken: token)
> account.addDocument(document)

I have, but I always feel a tinge of guilt when I do it. I know I shouldn’t.

Fortunately, karma is satisfied because Xcode autocomplete punishes me by 
always putting the capitalised version as the top choice.


> 
> -- 
> Brent Royal-Gordon
> Sent from my iPhone
> 
> ___
> 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] Eliminate the "T1 -> T2" syntax, require "(T1) -> T2"

2016-04-21 Thread Jeremy Pereira via swift-evolution

> On 20 Apr 2016, at 15:40, Erica Sadun  wrote:
> 
> 
>> On Apr 20, 2016, at 5:09 AM, Jeremy Pereira 
>>  wrote:
>> 
>> 
>>> On 19 Apr 2016, at 17:24, Erica Sadun via swift-evolution 
>>>  wrote:
>>> 
 
>>> Short of a complete rethink of closure syntax, requiring parentheses there 
>>> would not improve the language in any measurable way.
>> 
>> Does requiring the parentheses in (T1) -> T2 improve the language in any 
>> measurable way?
> 
> I believe it does, as the parens are already required at call sites and in 
> function declarations, and when using functions with more than one argument.

I’m sorry, but the one statement does not follow from the other. That 
parentheses are required at call sites and in function declarations (NB: but 
not in closure definitions) does not imply that the language would be 
measurably improved by mandating them in function type declarations of the form 
T1 -> T2 as well.

In fact, it seems to me, that, generally, the language designers took the 
opposite point of view, namely that the language is measurably improved by 
allowing coders to omit syntax where the omission does not result in ambiguity. 
For instance, we can omit the statement terminator for the last statement on a 
line, type annotations for let and var identifiers where the type can be 
inferred, pretty much everything in a closure’s parameter and return type 
declaration.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread James Froggatt via swift-evolution
I sometimes find myself wanting to use private protocols + extensions to try to 
add public functions to a set of types. Something like this:

private protocol ArrayBackedType {
var data: [String] {get set}
}
public extension ArrayBackedType: UITableViewDataSource {
/*standard table view methods here*/
}

This would currently require two changes to the language: public extensions to 
private protocols, and support for ObjC-compatible functions in extensions 
(which should be possible for private/internal protocols).

Additionally, extensions could get the ability to add storage to the 
(non-imported) type they extend, so:

internal protocol ArrayBackedType {}
public extension ArrayBackedType: UITableViewDataSource {
private var data: [String] = []
dynamic func tableView(…)
}

The separate protocol & extension declarations could then get some syntactic 
sugar:

/*can't be public, since it can add properties, internal availability matches 
that of the protocol in the previous example*/
internal protocol extension ArrayBackedType { … }

or even more concisely:
internal trait ArrayBackedType { … }

Could traits be constructed from protocol extensions in this way, or otherwise 
end up competing with them if just some of these features were to be added? My 
concern is that adding traits as a separate language feature could put them in 
direct competition with protocol extensions.

 Begin Message  
Group: gmane.comp.lang.swift.evolution 
MsgID:  

Another traits implemenation

http://php.net/manual/en/language.oop5.traits.php
On Apr 21, 2016 5:53 PM, "Niall Young via swift-evolution" <
swift-evolution-m3fhrko0vlzytjvyw6y...@public.gmane.org> wrote:

>At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:
>
>I feel like the solution to the Arrow/Enemy problem that best fits with
>>Swift's current available tools is neither a protocol (which, as you
>>mentioned, doesn't get rid of the initialization/configuration of the
>>member data) or inheritance (which, as you mentioned, can only have one
>>base type) -- it's to extract a third type that handles
>>
>
>What you're describing sounds _exactly_ like Traits :-)
>
>http://scg.unibe.ch/research/traits
>
>Traits could be a peer of extensions, filling a niche that isn't quite the
>same niche as a default implementation, but it could be consistently and
>safely consumed like an extension, with its own rules of consumption
>(flattening) - to implement any need or explicit protocol requirement that
>a Class, Value Type or Protocol has at compile-time.
>
>Think of a Trait as providing a consumable set of functions.  Now imagine
>that we're combining the collective declarations of 1..N Traits all
>together, consumed by a Class or Value Type (or Protocol!) in a predicable
>and safe way (flattening: see the first Traits white paper).
>
>i.e. we get the same result regardless of the order of consumption, how
>many times any given Trait(s) were consumed, Traits dependent on other
>Traits etc.  Predictable results, given the same input we always get the
>same output.  This is flattening, but read the white papers for more detail.
>
>The process of flattening itself could be a peer of the existing rules
>around static dispatch vs. dynamic dispatch around
>default-implementations/extensions vs. class overrides.
>
>A Trait declaration could look something ~like:
>
>trait TraitX (ProtocolAdherenceY): DependentTrait1,
>DependentTrait2 {
>
>private var foo
>private let bah { .. }
>
>func fooify { .. }
>mutating func bahify { .. }
>private func hah { .. }
>
>}
>
>with a Trait being a closure, where _only private_ data Properties can be
>declared, providing 1..N function implementations.  It could conform
>_towards_ a Protocol (partial to full conformance), and also be dependent
>upon other names Traits, which would be consumed in parallel as a
>first-class citizen with the Trait that depends on it.
>
>Traits could be consumed by a class or value type, to provide function
>implementations which could be satisfying a Protocol implementation
>requirement, along with its own private functions and private data for its
>(private to Trait) local state etc.  The consumption syntax I'm still
>unsure of, but a clear declarative "flattens Trait1, Trait2, .. , TraitN"
>or similar would do.
>
>The consuming Class or Value Type would remain fully responsible for its
>own Protocol conformance, and if any of the consumed Trait public
>implementations conflict or overlap with each other, then the conflicts
>must be resolved explicitly by the Class or Value Type itself, where it is
>consumed.
>
>The resulting "flattened" set of Traits would be input towards the Type's
>own compiler requirements, with the author being required to explicitly
>resolve any and all conflicts at compile-time.  Cconsumption at run-time
>could be a later feature as Swift's core stabilises and specific run-time
>metaprogramming facilities are exposed.
>
>Explicit conflict reso

Re: [swift-evolution] Lazy var and deinit

2016-04-21 Thread Vladimir.S via swift-evolution
For exactly this example, from my point of view, b.clean() is actually 
using of the "b" property. Compiler, and I, don't know what '.clean()' 
means and actually it is the same as


deinit {
  b.doSomethingCool() // << shouldn't "b" created here to process your 
request?

}

But probably I understand the problem you are trying to solve.
How to check if lazy property/variable was actually initialized, so you can 
call its ".clean" only when it was really created and used. I.e. we just 
don't need to call b.clean if "b" was not even called and so was not created.


Right now I can't find a way to check this, probably I'm missing something..
So the question is : how to check if b was or was not actually "created" :
(something like)

deinit {
if let b {
b.clean()
}
}

Anyone?

On 21.04.2016 13:27, Alexandr.moq via swift-evolution wrote:

Should SWIFT initialize a variable in deinit method if it has not been 
initialized?

For example:
```swift
class A {
lazy var b = B()
deinit {
b.clean()
}
}
var a = A()
a.b.doSomething() //1: variable was created
a = A() //2: "clean" method was called for "b" variable
a = A() //3: instance of A from step 2 should killed and "deinit" method is called. In this method 
"b" variable will be created, "clean" will be called and "b" will be killed. So, is it ok 
or better if swift doesn’t create lazy variables in deinit if variable is not created yet
```
To be honest, I don’t know which topic I should use. Because I don’t know, it’s 
propose, bug or something else.
___
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] String(validatingUTF8:) doesn't

2016-04-21 Thread Drew Crawford via swift-evolution
CChar is typedefed to Int8 I believe.  So the CChar=>Int8 implicit conversion 
is not surprising.

The conversion from an [Int8] to an UnsafePointer is a bit of a sharper 
edge, although there are cases where it makes sense (e.g. calling to C).  
Importing C APIs with some kind of decl to opt into array-pointer conversion 
may make more sense than what we do now.

But independently of the language-level design problem, this is a bad API.  Its 
name does not describe what it does, It causes UB even though the word "unsafe" 
does not appear anywhere as is our convention, and quite frankly I don't 
understand why it is so important to have an API to work with CStrings when we 
could have an API to work with arrays in the standard library instead.  

I thought there might be a performance reason, but having read the sourcecode 
it looks O(N), so I am at a loss as to what problem this solves that an 
array-based API does not, that justifies the sharp edge of memory-unsafety.

Drew

> On Apr 21, 2016, at 5:23 AM, Vladimir.S  wrote:
> 
> How at all Swift allows such an implicit conversion from one type to another, 
> at the same time when we must explicitly convert let say Int8 to Int16 ???
> 
> I.e. this is not allowed
> 
> var i8 : Int8 = 10
> var i16 : Int16 = i8
> 
> But [Int8] to UnsafePointer - no problems.
> 
> It is very weird behavior in this case.
> 
> Anyone can explain why String(validatingUTF8:) should silently convert [Int8] 
> to UnsafePointer ??
> 
> On 21.04.2016 12:01, Drew Crawford via swift-evolution wrote:
>> I have just now for the second time root-caused yet another "nasty nasty UB
>> bug" from yet another developer who got cut on the very sharp edge of this 
>> API:
>> 
>>var result = [40,50,60] as [Int8]
>>return String(validatingUTF8: result)
>> 
>> This poorly-named String constructor does not take a Swift array of UTF8
>> bytes, it takes an UnsafePointer to a C string.  When that C string is not
>> null-terminated (as shown here), UB ensues.
>> 
>> I believe **at least** we need a sane name for this constructor like
>> String(validatingUTF8CString:) that vaguely suggests what the programmer
>> can do to avoid UB.
>> 
>> I further believe that this API is just plain bad, but swift-dev disagrees
>> and so in the interests of doing /something/ to stop the bleeding I propose
>> we rename.
>> 
>> Drew
>> 
>> 
>> ___
>> 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] Lazy var and deinit

2016-04-21 Thread Alexandr.moq via swift-evolution
Should SWIFT initialize a variable in deinit method if it has not been 
initialized? 

For example: 
```swift
class A {
lazy var b = B()
deinit {
b.clean()
}
}
var a = A()
a.b.doSomething() //1: variable was created
a = A() //2: "clean" method was called for "b" variable
a = A() //3: instance of A from step 2 should killed and "deinit" method is 
called. In this method "b" variable will be created, "clean" will be called and 
"b" will be killed. So, is it ok or better if swift doesn’t create lazy 
variables in deinit if variable is not created yet
```
To be honest, I don’t know which topic I should use. Because I don’t know, it’s 
propose, bug or something else.
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] String(validatingUTF8:) doesn't

2016-04-21 Thread Vladimir.S via swift-evolution
How at all Swift allows such an implicit conversion from one type to 
another, at the same time when we must explicitly convert let say Int8 to 
Int16 ???


I.e. this is not allowed

var i8 : Int8 = 10
var i16 : Int16 = i8

But [Int8] to UnsafePointer - no problems.

It is very weird behavior in this case.

Anyone can explain why String(validatingUTF8:) should silently convert 
[Int8] to UnsafePointer ??


On 21.04.2016 12:01, Drew Crawford via swift-evolution wrote:

I have just now for the second time root-caused yet another "nasty nasty UB
bug" from yet another developer who got cut on the very sharp edge of this API:

var result = [40,50,60] as [Int8]
return String(validatingUTF8: result)

This poorly-named String constructor does not take a Swift array of UTF8
bytes, it takes an UnsafePointer to a C string.  When that C string is not
null-terminated (as shown here), UB ensues.

I believe **at least** we need a sane name for this constructor like
String(validatingUTF8CString:) that vaguely suggests what the programmer
can do to avoid UB.

I further believe that this API is just plain bad, but swift-dev disagrees
and so in the interests of doing /something/ to stop the bleeding I propose
we rename.

Drew


___
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] Localization support for string interpolation

2016-04-21 Thread Adrian Zubarev via swift-evolution
I know that :D I mean < and > are considered as normal characters of the string 
"<\(quote)> by <\(person)>“ so thats why this won’t work that way.

-- 
Adrian Zubarev

Am 21. April 2016 bei 11:32:05, Daniel Höpfl via swift-evolution 
(swift-evolution@swift.org) schrieb:

Maybe using "<\(quote)> by <\(person)>" ___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread Tim Hawkins via swift-evolution
Another traits implemenation

http://php.net/manual/en/language.oop5.traits.php
On Apr 21, 2016 5:53 PM, "Niall Young via swift-evolution" <
swift-evolution@swift.org> wrote:

> At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:
>
> I feel like the solution to the Arrow/Enemy problem that best fits with
>> Swift's current available tools is neither a protocol (which, as you
>> mentioned, doesn't get rid of the initialization/configuration of the
>> member data) or inheritance (which, as you mentioned, can only have one
>> base type) -- it's to extract a third type that handles
>>
>
> What you're describing sounds _exactly_ like Traits :-)
>
> http://scg.unibe.ch/research/traits
>
> Traits could be a peer of extensions, filling a niche that isn't quite the
> same niche as a default implementation, but it could be consistently and
> safely consumed like an extension, with its own rules of consumption
> (flattening) - to implement any need or explicit protocol requirement that
> a Class, Value Type or Protocol has at compile-time.
>
> Think of a Trait as providing a consumable set of functions.  Now imagine
> that we're combining the collective declarations of 1..N Traits all
> together, consumed by a Class or Value Type (or Protocol!) in a predicable
> and safe way (flattening: see the first Traits white paper).
>
> i.e. we get the same result regardless of the order of consumption, how
> many times any given Trait(s) were consumed, Traits dependent on other
> Traits etc.  Predictable results, given the same input we always get the
> same output.  This is flattening, but read the white papers for more detail.
>
> The process of flattening itself could be a peer of the existing rules
> around static dispatch vs. dynamic dispatch around
> default-implementations/extensions vs. class overrides.
>
> A Trait declaration could look something ~like:
>
> trait TraitX (ProtocolAdherenceY): DependentTrait1,
> DependentTrait2 {
>
> private var foo
> private let bah { .. }
>
> func fooify { .. }
> mutating func bahify { .. }
> private func hah { .. }
>
> }
>
> with a Trait being a closure, where _only private_ data Properties can be
> declared, providing 1..N function implementations.  It could conform
> _towards_ a Protocol (partial to full conformance), and also be dependent
> upon other names Traits, which would be consumed in parallel as a
> first-class citizen with the Trait that depends on it.
>
> Traits could be consumed by a class or value type, to provide function
> implementations which could be satisfying a Protocol implementation
> requirement, along with its own private functions and private data for its
> (private to Trait) local state etc.  The consumption syntax I'm still
> unsure of, but a clear declarative "flattens Trait1, Trait2, .. , TraitN"
> or similar would do.
>
> The consuming Class or Value Type would remain fully responsible for its
> own Protocol conformance, and if any of the consumed Trait public
> implementations conflict or overlap with each other, then the conflicts
> must be resolved explicitly by the Class or Value Type itself, where it is
> consumed.
>
> The resulting "flattened" set of Traits would be input towards the Type's
> own compiler requirements, with the author being required to explicitly
> resolve any and all conflicts at compile-time.  Cconsumption at run-time
> could be a later feature as Swift's core stabilises and specific run-time
> metaprogramming facilities are exposed.
>
> Explicit conflict resolution, via a flattened 2D matrix of Trait:func
> identifying conflicts that need to be resolved by the consumer, also gives
> reliable results with no cognitive overhead as Brian's identified in
> resolving Mixin consumption.  Plus there is no diamond-problem, as there is
> no inheritance.  With Traits, it _must_ be resolved explicitly in code,
> with suitable compiler errors for malformed Types that have consumed 1..N
> Trait(s).
>
> Stateful Traits suggest that as long as the data is private _to the Trait_
> then we can safely ignore some of the complexity of state in Traits - it
> just isn't exposed as the Trait declaration itself is a closure.
> Dependency on state in the consumer could proxy to
> class/instance/value-type data via Protocol.
>
> Swift and Protocols seem like a perfect match for "capital-T" Traits.  Any
> thoughts on if this is suitable for a 3.0 or 4.0 Proposal?
>
> I've recently built similar mechanisms exploring these concepts with basic
> metaprogramming and a common root class in a dynamic language, but as a
> core language feature of Swift I think it could very much complement the
> existing protocols and extension concepts, with 1..N re-usable
> implementations, and it also could help to resolves the uncertainty/rules
> around static vs. dynamic dispatch: static could remain the domain of
> extensions / default implementations

Re: [swift-evolution] [Draft] Mixins

2016-04-21 Thread Niall Young via swift-evolution

At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:


I feel like the solution to the Arrow/Enemy problem that best fits with
Swift's current available tools is neither a protocol (which, as you
mentioned, doesn't get rid of the initialization/configuration of the
member data) or inheritance (which, as you mentioned, can only have one
base type) -- it's to extract a third type that handles


What you're describing sounds _exactly_ like Traits :-)

http://scg.unibe.ch/research/traits

Traits could be a peer of extensions, filling a niche that isn't quite the same 
niche as a default implementation, but it could be consistently and safely 
consumed like an extension, with its own rules of consumption (flattening) - to 
implement any need or explicit protocol requirement that a Class, Value Type or 
Protocol has at compile-time.

Think of a Trait as providing a consumable set of functions.  Now imagine that 
we're combining the collective declarations of 1..N Traits all together, 
consumed by a Class or Value Type (or Protocol!) in a predicable and safe way 
(flattening: see the first Traits white paper).

i.e. we get the same result regardless of the order of consumption, how many 
times any given Trait(s) were consumed, Traits dependent on other Traits etc.  
Predictable results, given the same input we always get the same output.  This 
is flattening, but read the white papers for more detail.

The process of flattening itself could be a peer of the existing rules around 
static dispatch vs. dynamic dispatch around default-implementations/extensions 
vs. class overrides.

A Trait declaration could look something ~like:

trait TraitX (ProtocolAdherenceY): DependentTrait1, DependentTrait2 {

private var foo
private let bah { .. }

func fooify { .. }
mutating func bahify { .. }
private func hah { .. }

}

with a Trait being a closure, where _only private_ data Properties can be 
declared, providing 1..N function implementations.  It could conform _towards_ 
a Protocol (partial to full conformance), and also be dependent upon other 
names Traits, which would be consumed in parallel as a first-class citizen with 
the Trait that depends on it.

Traits could be consumed by a class or value type, to provide function implementations 
which could be satisfying a Protocol implementation requirement, along with its own 
private functions and private data for its (private to Trait) local state etc.  The 
consumption syntax I'm still unsure of, but a clear declarative "flattens Trait1, 
Trait2, .. , TraitN" or similar would do.

The consuming Class or Value Type would remain fully responsible for its own 
Protocol conformance, and if any of the consumed Trait public implementations 
conflict or overlap with each other, then the conflicts must be resolved 
explicitly by the Class or Value Type itself, where it is consumed.

The resulting "flattened" set of Traits would be input towards the Type's own 
compiler requirements, with the author being required to explicitly resolve any and all 
conflicts at compile-time.  Cconsumption at run-time could be a later feature as Swift's 
core stabilises and specific run-time metaprogramming facilities are exposed.

Explicit conflict resolution, via a flattened 2D matrix of Trait:func 
identifying conflicts that need to be resolved by the consumer, also gives 
reliable results with no cognitive overhead as Brian's identified in resolving 
Mixin consumption.  Plus there is no diamond-problem, as there is no 
inheritance.  With Traits, it _must_ be resolved explicitly in code, with 
suitable compiler errors for malformed Types that have consumed 1..N Trait(s).

Stateful Traits suggest that as long as the data is private _to the Trait_ then 
we can safely ignore some of the complexity of state in Traits - it just isn't 
exposed as the Trait declaration itself is a closure.  Dependency on state in 
the consumer could proxy to class/instance/value-type data via Protocol.

Swift and Protocols seem like a perfect match for "capital-T" Traits.  Any 
thoughts on if this is suitable for a 3.0 or 4.0 Proposal?

I've recently built similar mechanisms exploring these concepts with basic 
metaprogramming and a common root class in a dynamic language, but as a core 
language feature of Swift I think it could very much complement the existing 
protocols and extension concepts, with 1..N re-usable implementations, and it 
also could help to resolves the uncertainty/rules around static vs. dynamic 
dispatch: static could remain the domain of extensions / default 
implementations; with dynamic dispatch available to Classes and Traits?

More Reading:

http://scg.unibe.ch/research/traits

Cheers,

--
Niall Young
ni...@iinet.net.au


At Tue Mar 1 19:00:21 CST 2016, Brian Pratt brian at pratt.io wrote:


I think this sort of composition is preferable to inheritance in a lot of

Re: [swift-evolution] Localization support for string interpolation

2016-04-21 Thread Daniel Höpfl via swift-evolution

Hi Adrian,

"\(key)" is already part of Swift (see 
).


Maybe using "<\(quote)> by <\(person)>" as example was not the best 
idea, I should have used "“\(quote)” by \(person)". I changed the gist 
accordingly.



On 2016-04-21 11:21, Adrian Zubarev wrote:

I took a quick look at your proposal and one thing I didn’t liked
was the string itsel: "some text <\(key)>“

This looks odd to me. I’d suggest something like "some text
@(key)“ or "some text \[key]“ instead. But it is not up to me.

--
Adrian Zubarev
Am 21. April 2016 bei 09:42:18, Daniel Höpfl via swift-evolution
(swift-evolution@swift.org) schrieb:


Hi there!

TL;DR: Here’s my idea for a better localized strings handling in
Swift.
It includes both, support for string interpolation support for
NSLocalizedString, and a new string delimiter `...` that can be used
instead of NSLocalizedString("...").

Markdown hard to read? See


Greetings,
Daniel

# Localization support for string interpolation

## Introduction

I'd like to see some kind of advanced localization support in the
Swift
standard library. Currently all we have is what Cocoa provides but
that
does not work well with string interpolation. More or less, you can
not
use string interpolation if you have to use `NSLocalizedString` and
friends.

[I implemented a proof of
concept](https://github.com/dhoepfl/DHLocalizedString),
`DHLocalizedString`, that fills this gap. I would like to see
something
similar being part of the Swift standard library. While it is
possible
to implement localized strings as a custom library, this lacks
support
from genstring and other tools.

I’m not sure if `NSLocalizedString` is considered part of the
Swift
standard library (being part of Foundation Functions). Since there
is
decent Unicode-string support in Swift, I would like to see
localization
as part of the language, too. This proposal also includes a new
string
delimiter `` ` `` that deeply integrate localized strings in the
language.

## Motivation

String interpolation greatly simplyfies text handling but makes it
hard
to localize. You can not pass a string with interpolation to
`NSLocalizedString` because the key could be unpredictable.

## Proposed solution

`NSLocalizedString` should be extended to work with string
interpolation:

```swift
let quote = "Never trust the internet!"
let person = "Albert Einstein"
print(NSLocalizedString("<\(quote)> by <\(person)>"));
```

should look up the key:

```"<%@> by <%@>" = "%2$@ said: “%1$@”";```

and print:

```Albert Einstein said: “Never trust the internet!”```

So, `NSLocalizedString` (and friends) would “just work” with
string
interpolation. I’m not sure about the key format to use but my
proof of
concept simply replaces every interpolation with `%@` which seems
reasonable.

The proof of concept also includes an postfix operator `|~` (think
of a
flag) to reduce the impact localized strings have in line length.
Actually, I would love to replace `"` by a different marker (e.g.
`~|string|~`, `''string''`, ``` ``string`` ```, or `` `string` ``?)
for
localized strings. Imagine you could write the previous example as:

```swift
print(`<\(quote)> by <\(person)>`);
```

This syntax needs some work on how to specify `tableName:`,
`bundle:`,
and `comment:`. For `tableName:` and `bundle:`, I'd love to have a
construct to specify it for all localization tags within the file
(e.g.
`#localization(tableName: ..., bundle: ...)`).

If Swift gets multiline strings (`"""string"""`), `` `string` ``
could
also have  ```multiline``` .

## Impact on existing code

I see very little impact. There might be code out there that uses a
interpolated string as argument for `NSLocalizedString`. The key
used in
this case would change, breaking the translation. It would be
possible
to include a check for interpolated strings as arguments to
`NSLocalizedString` calls in the code update tool.

## Alternatives considered

### Use `NSLocalizedString` as is

One can use `NSLocalizedString` as it was used in Objective-C but
this
means that string interpolation cannot be used.

### `localized()` function for String class

I did not find a way how to get the function called before the
string
interpolation took place. (`"<\(quote)> by
<\(person)>".localized()`)

### Custom function

See above: The drawbacks are: Not having support in standard tools
and
the operator syntax not being as good as it could be.

___
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] [Discussion] Enforce argument labels on tuples

2016-04-21 Thread Adrian Zubarev via swift-evolution
Personally I'm fine with the way it is right now, but I do miss enforced labels 
at some point. At least it would be 'nice to have' feature like we already have 
@autoclosure or @noescape to enforce some specific behaviour.

I started the discussion about enforcing argument labels on tuples but with 
your feedback I totally see the point why this shouldn’t be something backed 
inside the language by default.

Optional way to enforce the usage of correct/strict/explicit labels could 
provide better readability from my point of view.

Remember the idea of cascading methods/initializer? For class types it’s almost 
possible to build that feature by yourself, but there is one problem that was 
discussed back then. What do we use inside the trailing closure to access the 
instance. 
Sure we could give it a custom name or just use `$0`.

```swift
let instance = ClassA() {

      // customName in
      // or $0
}

// imagine we had something optional like
class ClassB {

      @require_explicit_label_usage
      init(closure: (this: ClassB) -> Void) {

            closure(this: self)
      }
      func foo() {}
}

// now we could use it like

let b = ClassB() { this in // can be omitted due the use of 
@require_explicit_label_usage

       this.foo()
}

// I'll use ++ operator just for the example here

@require_explicit_label_usage
prefix func ++ (tuple: (exp: Int, earned: Int)) -> Int {

     return tuple.apples + tuple.amount
}

// this operator will only overload when the right labeling is applied to the 
tuple

++(exp: 10, earned: 5) // result would be 15

// the operator wont work with
++(100, 50)
// give another dev this snippet and ask him what 100 and 50 means

```
This example is very abstract but I'm sure you should get the point of the 
possible need of an optional label enforcement.

By the way, why does Swift allow something like this anyway?

var a = (a: 10) // is of type Int

Where something like the next example is not allowed at all:

var a: (a: Int) = (a: 10)


-- 
Adrian Zubarev

Am 21. April 2016 bei 09:14:16, Haravikk via swift-evolution 
(swift-evolution@swift.org) schrieb:

I think the important thing to remember is that the label check is intended to 
prevent cases like this:

let a:(left:Int, right:Int) = (1, 2)
var b:(right:Int, left:Int) = a

While the two tuples are compatible by type, the meaning of the values may 
differ due to the different labels; in this case the values are represented in 
a different order that a developer should have to explicitly reverse to ensure 
they aren’t making a mistake, or they could represent radically different 
concepts altogether.

It’s certainly annoying when the labels are only different due to minor 
differences, but the compiler doesn’t know that. So yeah, I think that in any 
case where there are external labels that differ a warning should be raised; 
this comes down to being able to later ignore types of warnings, which could 
avoid the boiler-plate in future.

The alternative would be if we had some syntax for mapping parameters more 
cleanly, for example:

hi(1, y: 2, fn: sum1 where left = lhs, right = rhs)

Or something along those lines anyway?

On 21 Apr 2016, at 06:18, David Owens II via swift-evolution 
 wrote:


On Apr 20, 2016, at 4:47 PM, Chris Lattner  wrote:

On Apr 20, 2016, at 12:31 PM, David Owens II via swift-evolution 
 wrote:
This is similar to another concern I raised with functions and being able to 
essentially erase the function argument names and apply two different named 
parameters just because their types match.

It seems reasonable to me that you can go from (x: Int, y: Int) => (Int, Int). 
However, going from (x: Int, y: Int) => (a: Int, b: Int) feels somewhat odd. 
Yes, the types can obviously slot in there fine, but how much importance do the 
labels for the types bring to the table?

Similarly, should this (Int, Int) => (x: Int, y: Int) be allowed through an 
implicit means? If so, then it's really just an intermediate step for (x: Int, 
y: Int) => (a: Int, b: Int) working.

I completely agree, I think it makes sense to convert from unlabeled to labeled 
(or back) but not from “labeled" to "differently labeled”.

So what matters more, type signatures or label names?

Here's an example:

typealias Functor = (left: Int, right: Int) -> Int

func hi(x: Int, y: Int, fn: Functor) -> Int {
    return fn(left: x, right: y)
}

hi(1, y: 2, fn: +)
hi(1, y: 2, fn: *)

If we say that the parameter names are indeed vital, then the above code cannot 
work as the operators that match the type signature are defined as: 

public func +(lhs: Int, rhs: Int) -> Int

Obviously, given a name to the parameter brings clarity and can be self 
documenting, but if we want the above to work while making names just as vital 
as the type signature, then we need to declare `Functor` as such:

typealias Functor = (_ left: Int, _ right: Int) -> Int

However, that's not even legal code today, and even if it were, is that really 
better?

I don’t

[swift-evolution] String(validatingUTF8:) doesn't

2016-04-21 Thread Drew Crawford via swift-evolution
I have just now for the second time root-caused yet another "nasty nasty UB 
bug" from yet another developer who got cut on the very sharp edge of this API:

var result = [40,50,60] as [Int8]
return String(validatingUTF8: result)

This poorly-named String constructor does not take a Swift array of UTF8 bytes, 
it takes an UnsafePointer to a C string.  When that C string is not 
null-terminated (as shown here), UB ensues.

I believe *at least* we need a sane name for this constructor like 
String(validatingUTF8CString:) that vaguely suggests what the programmer can do 
to avoid UB.

I further believe that this API is just plain bad, but swift-dev disagrees and 
so in the interests of doing something to stop the bleeding I propose we rename.

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


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0068: Expanding Swift Self to class members and value types

2016-04-21 Thread Sebastian Hagedorn via swift-evolution

>   * What is your evaluation of the proposal?

Generally +1, but disagree on the naming.

>   * 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?

Generally, yes. However, I don’t think “Self” is very readable or easily 
understandable. “dynamicType” on the other hand can hardly be misunderstood. 
With Self, one first has to know/understand that there is a difference between 
static and dynamic types, and then know/look up which of these types is 
returned. With dynamicType, this is clear from the beginning. If you don’t know 
what a dynamic type is, you will stumble over the word and there’s a much 
higher chance you’d do the research. I don’t think we should value 
upper/lowercase consistency higher than readability of the code (including what 
it actually does).

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

ObjC, but I don’t think this compares well, as type lookup at runtime is only 
available for classes.

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

Read the proposal and all replies that have come in since.

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


[swift-evolution] Localization support for string interpolation

2016-04-21 Thread Daniel Höpfl via swift-evolution
Hi there!

TL;DR: Here’s my idea for a better localized strings handling in Swift.
It includes both, support for string interpolation support for
NSLocalizedString, and a new string delimiter `...` that can be used
instead of NSLocalizedString("...").

Markdown hard to read? See


Greetings,
   Daniel


# Localization support for string interpolation

## Introduction

I'd like to see some kind of advanced localization support in the Swift
standard library. Currently all we have is what Cocoa provides but that
does not work well with string interpolation. More or less, you can not
use string interpolation if you have to use `NSLocalizedString` and friends.

[I implemented a proof of
concept](https://github.com/dhoepfl/DHLocalizedString),
`DHLocalizedString`, that fills this gap. I would like to see something
similar being part of the Swift standard library. While it is possible
to implement localized strings as a custom library, this lacks support
from genstring and other tools.

I’m not sure if `NSLocalizedString` is considered part of the Swift
standard library (being part of Foundation Functions). Since there is
decent Unicode-string support in Swift, I would like to see localization
as part of the language, too. This proposal also includes a new string
delimiter `` ` `` that deeply integrate localized strings in the language.

## Motivation

String interpolation greatly simplyfies text handling but makes it hard
to localize. You can not pass a string with interpolation to
`NSLocalizedString` because the key could be unpredictable.

## Proposed solution

`NSLocalizedString` should be extended to work with string interpolation:

```swift
let quote = "Never trust the internet!"
let person = "Albert Einstein"
print(NSLocalizedString("<\(quote)> by <\(person)>"));
```

should look up the key:

```"<%@> by <%@>" = "%2$@ said: “%1$@”";```

and print:

```Albert Einstein said: “Never trust the internet!”```

So, `NSLocalizedString` (and friends) would “just work” with string
interpolation. I’m not sure about the key format to use but my proof of
concept simply replaces every interpolation with `%@` which seems
reasonable.

The proof of concept also includes an postfix operator `|~` (think of a
flag) to reduce the impact localized strings have in line length.
Actually, I would love to replace `"` by a different marker (e.g.
`~|string|~`, `''string''`, ``` ``string`` ```, or `` `string` ``?) for
localized strings. Imagine you could write the previous example as:

```swift
print(`<\(quote)> by <\(person)>`);
```

This syntax needs some work on how to specify `tableName:`, `bundle:`,
and `comment:`. For `tableName:` and `bundle:`, I'd love to have a
construct to specify it for all localization tags within the file (e.g.
`#localization(tableName: ..., bundle: ...)`).

If Swift gets multiline strings (`"""string"""`), `` `string` `` could
also have  ```multiline``` .

## Impact on existing code

I see very little impact. There might be code out there that uses a
interpolated string as argument for `NSLocalizedString`. The key used in
this case would change, breaking the translation. It would be possible
to include a check for interpolated strings as arguments to
`NSLocalizedString` calls in the code update tool.

## Alternatives considered

### Use `NSLocalizedString` as is

One can use `NSLocalizedString` as it was used in Objective-C but this
means that string interpolation cannot be used.

### `localized()` function for String class

I did not find a way how to get the function called before the string
interpolation took place. (`"<\(quote)> by <\(person)>".localized()`)

### Custom function

See above: The drawbacks are: Not having support in standard tools and
the operator syntax not being as good as it could be.

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


Re: [swift-evolution] [Review] SE-0068: Expanding Swift Self to class members and value types

2016-04-21 Thread Vladimir.S via swift-evolution
I believe we just have to separate these concepts explicity : i.e. 
"dynamicType" and "Self"(as replacement for type name in protocol)


Yes, seems like we need Self and #Self to separate these. Or we should 
select a better names, if we have better suggestions.


On 20.04.2016 23:27, Erica Sadun via swift-evolution wrote:



On Apr 20, 2016, at 12:37 PM, Dave Abrahams via swift-evolution 
 wrote:


on Wed Apr 20 2016, Chris Lattner  wrote:


Hello Swift community,

The review of "SE-0068: Expanding Swift Self to class members and value types"
begins now and runs through April 25. The proposal is available here:

https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md


Caveat: somewhat scattered response, probably after insufficient
review; apply salt liberally.

This looks like a good idea overall to me, but I think it may leave
important uses for Self on the floor.  For example, I still want to
write this:

 struct SomeType {
   func f(x: Self) {}
 }

Does the proposal make that work in some way that I've overlooked?

IMO it's a shame that you can't take a protocol body, dump it into your
type's body, and fill in the implementations to satisfy a conformance
without finding all the instances of “Self” and replacing them with your
type's name, and it would be sad if this proposal didn't address that
somehow.  In general, I'm concerned that we may be making “Self” mean
two very different things in different contexts: IIUC one is a type
that's fully-resolved at compile time, and the other one is a value that
holds a metatype.  If there were less of a wall between the two
uses/contexts, that would make the proposal more palatable to me.


It kind of did address this until late last night. I was worried that proposing 
#Self and Self at the
same time would be divisive. The point of #Self would be a compile-time 
replacement of the name
of the defining type, vs the run-time evaluation of Self. Trying to propose two 
things at once
seemed like a difficult sell.

If there's sufficient support for doing so, I can add it back in as a revision 
to the proposal if
the core team requests it.

-- 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] [Idea] Passing an Array to Variadic Functions

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

On 20.04.2016 23:27, Slava Pestov wrote:



On Apr 19, 2016, at 10:54 AM, Haravikk via swift-evolution
mailto:swift-evolution@swift.org>> wrote:

  * Possibly optimisations unavailable to Array passing?


Indeed, it should be possible to implement varargs by allocating the
argument array on the stack (and having the compiler implicitly copy it to
the heap inside the callee if it escapes). Although you can imagine this
type of optimization being performed for arbitrary arrays, it would be more
difficult and less predictable.


But what about situations when we need to pass an array to function that 
accepts only variadic params? Don't we need some #splat() function?




Slava



*Cons*:

  * Doesn’t do anything that passing an array directly can’t.
  * Passing an array is actually slightly more flexible (can dynamically
pass more or less arguments as required at the call site).
  * Less explicit type at call site; gives the appearance of passing
instance(s) of Foo, rather than one instance of [Foo], can lead to
ambiguity with overloaded functions.
  * Extra syntax to support (enabling array passing would be more code
required to support this feature)


I’d also argue that variadic functions increase the learning curve, as
the first time you’re presented with one it isn’t necessarily clear what
it does unless you’ve encountered them before. Like I say it can be
ambiguous at the call-site in particular, as it doesn’t show that an
array of [Foo] is being passed as opposed to N instances of Foo (however
many are in the call).

While I’ve used them in the past, I’ve never really felt that they
simplify anything enough to justify them, as it’s just two square
brackets extra to pass an array; this is extra noise sure, but clarifies
what is actually happening.

So if variadic functions don’t have any other advantages, then it’s
really just a very minor piece of syntactic sugar that can lead to more
confusion, less explicit types in function calls, an extra piece of
syntax to parse and handle and possibly other features required to
support it better (like the one being inquired about). The only other
argument I can think of for them is that many other languages have them,
but that’s not important to me vs cutting out cruft.


Short version; removing variadic functions would solve the problem of
defining overloads for both variadic and array types by only ever
requiring the latter.

P.S- I’d also like to note that where possible people should be accepting
Sequences or Collections in their methods anyway rather than arrays
specifically, as it’s more flexible that way ;)
___
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-0068: Expanding Swift Self to class members and value types

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

I feel like we should separate all these self/Self/dynamicType explicity.

For example :

DynamicSelf - where we use "self.dynamicType" in instance methods and 
"self" in class/static methods


#ThisType (or #Type or #Self or ?) - where we need a replacement for "the 
exactly type name where this method is declared"


I.e. you'll have
  struct SomeType {
func f(x: #ThisType) {}
  }

protocol SomeProtocol {
  func f(x: #ThisType)
}

class SomeClass: SomeProtocol {
  func f(x: #ThisType) {   }
}

but

class SomeClass {
  class func classF() { DynamicSelf.someOtherClassF() }

  func f() {
DynamicSelf.someStaticMethod()
  }
}


On 20.04.2016 21:37, Dave Abrahams via swift-evolution wrote:


on Wed Apr 20 2016, Chris Lattner  wrote:


Hello Swift community,

The review of "SE-0068: Expanding Swift Self to class members and value types"
begins now and runs through April 25. The proposal is available here:

https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md


Caveat: somewhat scattered response, probably after insufficient
review; apply salt liberally.

This looks like a good idea overall to me, but I think it may leave
important uses for Self on the floor.  For example, I still want to
write this:

  struct SomeType {
func f(x: Self) {}
  }

Does the proposal make that work in some way that I've overlooked?

IMO it's a shame that you can't take a protocol body, dump it into your
type's body, and fill in the implementations to satisfy a conformance
without finding all the instances of “Self” and replacing them with your
type's name, and it would be sad if this proposal didn't address that
somehow.  In general, I'm concerned that we may be making “Self” mean
two very different things in different contexts: IIUC one is a type
that's fully-resolved at compile time, and the other one is a value that
holds a metatype.  If there were less of a wall between the two
uses/contexts, that would make the proposal more palatable to me.


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


Re: [swift-evolution] [Discussion] Enforce argument labels on tuples

2016-04-21 Thread Haravikk via swift-evolution
I think the important thing to remember is that the label check is intended to 
prevent cases like this:

let a:(left:Int, right:Int) = (1, 2)
var b:(right:Int, left:Int) = a

While the two tuples are compatible by type, the meaning of the values may 
differ due to the different labels; in this case the values are represented in 
a different order that a developer should have to explicitly reverse to ensure 
they aren’t making a mistake, or they could represent radically different 
concepts altogether.

It’s certainly annoying when the labels are only different due to minor 
differences, but the compiler doesn’t know that. So yeah, I think that in any 
case where there are external labels that differ a warning should be raised; 
this comes down to being able to later ignore types of warnings, which could 
avoid the boiler-plate in future.

The alternative would be if we had some syntax for mapping parameters more 
cleanly, for example:

hi(1, y: 2, fn: sum1 where left = lhs, right = rhs)

Or something along those lines anyway?

> On 21 Apr 2016, at 06:18, David Owens II via swift-evolution 
>  wrote:
> 
>> 
>> On Apr 20, 2016, at 4:47 PM, Chris Lattner > > wrote:
>> 
>> On Apr 20, 2016, at 12:31 PM, David Owens II via swift-evolution 
>> mailto:swift-evolution@swift.org>> wrote:
>>> This is similar to another concern I raised with functions and being able 
>>> to essentially erase the function argument names and apply two different 
>>> named parameters just because their types match.
>>> 
>>> It seems reasonable to me that you can go from (x: Int, y: Int) => (Int, 
>>> Int). However, going from (x: Int, y: Int) => (a: Int, b: Int) feels 
>>> somewhat odd. Yes, the types can obviously slot in there fine, but how much 
>>> importance do the labels for the types bring to the table?
>>> 
>>> Similarly, should this (Int, Int) => (x: Int, y: Int) be allowed through an 
>>> implicit means? If so, then it's really just an intermediate step for (x: 
>>> Int, y: Int) => (a: Int, b: Int) working.
>> 
>> I completely agree, I think it makes sense to convert from unlabeled to 
>> labeled (or back) but not from “labeled" to "differently labeled”.
>> 
>>> So what matters more, type signatures or label names?
>>> 
>>> Here's an example:
>>> 
>>> typealias Functor = (left: Int, right: Int) -> Int
>>> 
>>> func hi(x: Int, y: Int, fn: Functor) -> Int {
>>> return fn(left: x, right: y)
>>> }
>>> 
>>> hi(1, y: 2, fn: +)
>>> hi(1, y: 2, fn: *)
>>> 
>>> If we say that the parameter names are indeed vital, then the above code 
>>> cannot work as the operators that match the type signature are defined as: 
>>> 
>>> public func +(lhs: Int, rhs: Int) -> Int
>>> 
>>> Obviously, given a name to the parameter brings clarity and can be self 
>>> documenting, but if we want the above to work while making names just as 
>>> vital as the type signature, then we need to declare `Functor` as such:
>>> 
>>> typealias Functor = (_ left: Int, _ right: Int) -> Int
>>> 
>>> However, that's not even legal code today, and even if it were, is that 
>>> really better?
>> 
>> I don’t think this follows, since operator parameters are always unlabeled.  
>> I suspect we don’t reject it, but I’d be in favor of rejecting:
>> 
>> func +(lhs xyz: Int, rhs abc: Int) -> Int { }
> 
> So maybe I think about this incorrectly, but I always think of any parameter 
> without an explicit label to have one that is equal to the parameter name. So 
> these two functions signatures would be equivalent:
> 
> func sum1(lhs: Int, rhs: Int) -> Int
> func sum2(lhs lhs: Int, rhs rhs: Int) -> Int
> 
> It’s only when you explicit “erase” the label where there is none:
> 
> func sum(_ lhs: Int, _ rhs: Int) -> Int
> 
> So back to the example above, it’s still somewhat odd that all of these are 
> valid:
> 
> hi(1, y: 2, fn: sum1)
> hi(1, y: 2, fn: sum2)
> hi(1, y: 2, fn: sum)   // makes the most sense, no label to labeled promotion
> 
> But if we did reject the differently labeled version, that would mean that we 
> would need to declare the `Functor` above as:
> 
> typealias Functor = (Int, Int) -> Int
> 
> Is that better? I’m not terribly convinced that it is.
> 
> If `Functor` keeps the labels, I suspect it would just lead to additional 
> boiler-plate code that would look like:
> 
> typealias Functor = (left: Int, right: Int) -> Int
> 
> hi(1, y: 2, fn: { left, right in sum1(lhs: left, rhs: right) })
> 
> While it does seem technically correct, is that really the kind of code we 
> want in Swift? 
> 
> -David
> ___
> 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-evol

Re: [swift-evolution] [pitch] Eliminate the "T1 -> T2" syntax, require "(T1) -> T2"

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

In this particular case I belive

func foo(int: Int) -> (Int) -> (String) -> String

is much more explicit and clear about what is what :

foo(int: Int) returns not Int(that returns then String and then String).

foo(int: Int) return function with (Int) parameter, that return func with 
(String) parameter that returns single String value.



On 20.04.2016 20:53, Chris Lattner via swift-evolution wrote:



On Apr 20, 2016, at 8:46 AM, BJ Homer  wrote:

How would this proposal affect curried functions? Would this:

 func foo(int: Int) -> Int -> String -> String

become this?

 func foo(int: Int) -> (((Int) -> String) -> String)


No, it becomes:

func foo(int: Int) -> (Int) -> (String) -> String

-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] [SR-933] Rename flatten to flattened

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

On 20.04.2016 20:47, Dave Abrahams wrote:


on Tue Apr 19 2016, "Vladimir.S"  wrote:


Dave, could you clarify your message with more details please.
Are you saying that "map" will be "map" in Swift 3.0


That is the current plan of record.


Oh, thank you for clarifying this.




and that "flatten" is the same kind of special case when we don't need
to rename it?


Yes, “flatten” is in the same category because of its very close
semantic relationship to “map” and “flatMap.”

If it were not in this category I would want to rename it to
“flattenOneLevel” or “concatenateElements” or something, as I have
always felt the name “flatten” was insufficiently specific about its
semantics.  But it is, like “map,” “flatMap,” and “reduce,” a term of
art that many people would not recognize if we renamed it.


Just checked. Don't understand. In Swift 3.0 (mar 24) there are "map"
"filter" "reduce", not "mapped" etc as I though. IMO all this renaming
is becoming more and more strange. IMO We'll have inconsistent
language at the end. Or this is just old version of Swift 3.0 and
newer have "mapped" etc ? Confused.

Now in 3.0(mar 24), we have arr.sorted() but arr.map (not .mapped())
arr.filter (! I expect a mutating filtering of the arr itself
according to API Design Guidelines) etc.


I don't understand what you say you expect.



Well..
arr.sort() - mutating method. verb.
arr.sorted() - non-mutating. "..ed"
and..
arr.filter() - non-mutating. verb. I think a user who read API Design 
Guidelines can expect arr.filter() will be a mutating method.




OK.. Could someone point to where "we" decided that map/filter/reduce
(and probably others) will not be renamed according Guidelines or
clarify the situation with renaming of map/filter/reduce ? Thank you.


“We” decided it when the changes to the standard library to make it
conform to the API guidelines were put up for review and the changes
were accepted.  In those changes, map/filter/reduce/flatMap/flatten all
retained their names.


Is it "SE-0006" ?
https://github.com/apple/swift-evolution/blob/master/proposals/0006-apply-api-guidelines-to-the-standard-library.md

Could you please point me to lines in this document where it says that 
"map/filter/reduce" are exceptions and we don't need to rename them to 
mapped/filtered/reduced ? Thank you.





On 20.04.2016 2:00, Dave Abrahams via swift-evolution wrote:

Cases like this are exactly why the API guidelines have a “Use
terminology well” section.  “map” is provided for by that section.



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