Re: [swift-users] Compiler fLag to activate SE-0143 (conditional conformance)?

2017-12-17 Thread Slava Pestov via swift-users


> On Dec 14, 2017, at 7:42 PM, Dave Abrahams  wrote:
> 
> IMO it makes as much sense to mention the flag in the proposal as it does to 
> point at a proof-of-concept implementation that accompanies a proposal. 
> Generally we only accept proposals that “have an implementation” these days.  

I believe the proposal was accepted before the rule came into effect.

Slava___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Compiler fLag to activate SE-0143 (conditional conformance)?

2017-12-14 Thread Slava Pestov via swift-users


> On Dec 14, 2017, at 10:56 AM, torquato via swift-users 
>  wrote:
> 
> 
> SE-0143 has been accepted, but is not activated by default in the last 
> builds. As per Snapshot 2017-12-06 I get the Error message: "Conditional 
> conformance of 'Array' to 'Foo' depends on an experimental feature 
> (SE-0143)".
> Somewhere on the dev list archives I've read about a compiler flag that 
> activates this feature. I can't find it anymore. Bad Google-Fu.
> 
> Questions:
> 
> 1.)
> What is this compiler flag?

-enable-experimental-conditional-conformances

> 
> 2.)
> Shouldn't this (flag) be mentioned in the proposal? Or the Generics 
> Manifesto? Somewhere? At least for the meantime…?

I think until the flag is gone the proposal does not count as “implemented”.

> 
> 3.)
> What is the _real_ status of this proposal? Is it really accepted and going 
> into a next release or is this just a tryout that can be dropped any time?

It’s almost all implemented, except for dynamic casts to protocols that are 
conditionally conformed to. This part didn’t get finished before the 4.1 branch 
date so we put in the flag.

Slava

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

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


Re: [swift-users] Swift's method dispatch

2017-12-08 Thread Slava Pestov via swift-users
Hi Jens,

I think the problem is that overload ranking always prefers a protocol 
requirement to a protocol extension member, because usually you want the 
dynamic dispatch through the requirement instead of calling the default 
implementation. But it appears that this heuristic does not take into account 
the fact that the protocol extension member could be more constrained than the 
requirement.

Please file a bug, but it is unclear what the desired behavior actually is 
here. Perhaps it should just diagnose an ambiguity.

Slava

> On Dec 8, 2017, at 6:25 AM, Jens Persson via swift-users 
>  wrote:
> 
> Hi all!
> 
> Can someone please explain the rationale behind the last line printing
> "T is unknown"
> rather than (what I would expect):
> "T is Int"
> in the following program?
> 
> 
> protocol P {
> associatedtype T
> func f() // *
> }
> extension P {
> func f() { print("T is unknown") }
> }
> extension P where T == Int {
> func f() { print("T is Int") }
> }
> 
> struct X : P {}
> 
> struct Y where U: P, U.T == Int {
> // NOTE: The compiler/type-checker knows that U.T == Int here so ...
> typealias T = U.T
> var a: U
> func g() { a.f() } // ... how/why could this print anything but "T is 
> Int"?
> }
> 
> let x = X()
> x.f() // Prints "T is Int", no matter if * is commented out or not.
> 
> let y = Y(a: X())
> y.g() // Prints "T is unknown" unless * is commented out. Why?
> 
> 
> IMHO this looks like the compiler simply ignores that struct Y has the 
> constraint  U.T == Int.
> How else to explain this behavior?
> /Jens
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Multiple Class Types in Protocol Composition

2017-12-07 Thread Slava Pestov via swift-users
Hi Mario,

You’re right that this part of the proposal was not fully implemented. 
Computing the common ancestor of two superclasses is a little tricky here 
because it would force us to resolve the superclass type of a class when 
realizing a subclass existential. This would introduce circular dependencies. 
Either I missed something obvious or it would require some re-architecting of 
the type checker to make it work.

Either way, yes it’s a known limitation, but not one that is tracked by a JIRA 
presently, so please do file a bug!

Thanks,

Slava

> On Dec 7, 2017, at 7:17 AM, Mario Meili via swift-users 
>  wrote:
> 
> Hi everyone,
>  
> I noticed strange behaviour of the Swift 4.0.3 compiler regarding class and 
> subtype existentials.
>  
> According to the proposal SE-0156 
> (https://github.com/apple/swift-evolution/blob/master/proposals/0156-subclass-existentials.md
>  
> ),
>  multiple class types in protocol compositions should be allowed, if:
>  
> The class types are the same
> Or, one class type must be a subtype of the other.
>  
> However, when copying the exact code from the proposal into Xcode 9.2, the 
> result is the following:
>  
> 
>  
> My conclusion here is that the compiler does not allow multiple class types 
> in one protocol composition.
>  
> My question is:
> Is this behaviour intended or should I open a bug report?
>  
> Thank you very much
>  
> BR
> Mario
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 

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


Re: [swift-users] Experimenting with conditional conformances

2017-11-28 Thread Slava Pestov via swift-users
Hi Antonio,

This is explicitly mentioned in the original proposal. We do not allow multiple 
conditional conformances to be defined for the same type. Instead, is it 
possible to express your conformance as follows?

extension Array : Intertial where Element : Inertial { … }

Or do you really need different algorithms for Element == CGPoint and Element 
== [CGPoint], with no conformance for Element == [[CGPoint]], etc?

If the latter, you could possibly have an InertialElement protocol or similar 
that CGPoint and [CGPoint] conform to, with a second level of dispatch to pick 
between the two cases.

Slava

> On Nov 28, 2017, at 12:31 PM, Antonino Ficarra via swift-users 
>  wrote:
> 
> I’have a protocol:
> 
> protocol Inertial {
>   funcconvexHull( _ t:AffineTransform? ) -> [CGPoint]
>   funcarea( _ t:AffineTransform? ) -> CGFloat
>   funcfirstOrderMomentums( _ t:AffineTransform? ) -> 
> (x:CGFloat,y:CGFloat)
>   funcsecondOrderMomentums( _ t:AffineTransform? ) -> 
> (xx:CGFloat,xy:CGFloat,yy:CGFloat)
> }
> 
> I make [CPoint] (a poligon) conforms to the protocol:
> 
> extension Array : Inertial where Element == CGPoint {
> func convexHull(_ t: AffineTransform?) -> [CGPoint] {
> return ConvexHull.convexHull( points:self ).map { $0 * t }
> }
> 
> func area(_ t: AffineTransform?) -> CGFloat {
> return InertialUti.area( polig: self,t )
> }
> 
> func firstOrderMomentums(_ t: AffineTransform?) -> (x: CGFloat, y: 
> CGFloat) {
> return InertialUti.firstOrderMomentums( polig:self,t )
> }
> 
> func secondOrderMomentums(_ t: AffineTransform?) -> (xx: CGFloat, xy: 
> CGFloat, yy: CGFloat) {
> return InertialUti.secondOrderMomentums( polig:self,t )
> }
> }
> 
> 
> and work like a charm.
> 
> Then I try to make [[CPoint]] (an array of poligons) conforms to the same 
> protocol:
> 
> extension Array : Inertial where Element == [CGPoint] {
> var allVertexs : [CGPoint] {
> return flatMap({$0})
> }
> 
> func convexHull(_ t: AffineTransform?) -> [CGPoint] {
> return ConvexHull.convexHull( points:allVertexs ).map { $0 * t }
> }
> 
> func area(_ t: AffineTransform?) -> CGFloat {
> return InertialUti.area( poligs: self,t )
> }
> 
> func firstOrderMomentums(_ t: AffineTransform?) -> (x: CGFloat, y: 
> CGFloat) {
> return InertialUti.firstOrderMomentums( poligs:self,t )
> }
> 
> func secondOrderMomentums(_ t: AffineTransform?) -> (xx: CGFloat, xy: 
> CGFloat, yy: CGFloat) {
> return InertialUti.secondOrderMomentums( poligs:self,t )
> }
> }
> 
> but this isn’t permitted: Redundant conformance of 'Array' to 
> protocol ‘Inertial’ !
> 
> I think it's a severe limitation: array with different element’s type (i.e. 
> different specializations of the same generic type) should be treated as 
> distinct types and not as the same type.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Where to read about *.swiftmodule file format?

2017-11-28 Thread Slava Pestov via swift-users
Hi Volodymyr,

The format is not documented anywhere and is subject to change. A good starting 
point is include/swift/Serialization/ModuleFormat.h, but I would first be 
curious to know what exactly you’re planning on doing with it.

It might be better to extend swift-ide-test and similar utilities to dump the 
information you need in an easy to parse format, and exec() them from your IDE, 
instead of attempting to parse swift modules directly.

Slava

> On Nov 28, 2017, at 7:00 AM, Volodymyr B via swift-users 
>  wrote:
> 
> Hi
> 
> Where to read about *.swiftmodule file format?
> 
> And *.swiftdoc 
> 
> I want to understand container of it.
> 
> would be good to have parser for third party IDEs.
> 
> Best regards,
> Volodymyr Boichentsov
> 
> 
> 
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Functions getting compiled multiple times

2017-11-05 Thread Slava Pestov via swift-users


> On Nov 5, 2017, at 12:23 PM, Dan Stenmark via swift-users 
>  wrote:
> 
> I’ve recently been profiling our compile times using the 
> -debug-time-function-bodies flag, and I’ve noticed that some functions seem 
> to be listed multiple times.  I know that -debug-time-function-bodies isn’t 
> something that’s officially supported, but I’m not sure how to distinguish 
> between a bug in that versus a problem in our own project.
> 
> Is a function being listed multiple times expected behavior and, if so, what 
> does it indicate?

Can you give an example of such a function?

Slava

> 
> Dan
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] How to store ref to any kind of function, and call with it argument list?

2017-11-03 Thread Slava Pestov via swift-users
(Int) -> Int is not a subtype of (Any) -> Any, because a value of the latter 
type can be called with an argument type that is not an Int, for example a 
String:

let fn: (Int) -> Int = …
let fn2 = (Any) -> Any = fn // pretend this works

fn2(“hi”) // what does this do?

I think you’ll need to do something with generics where you wrap the original 
function value in a thunk that tests the argument type first, eg

func erase(fn: (T) -> U) -> (Any) -> Any {
  return { any in fn(arg as! T) }
}

I haven’t thought this through properly since it’s late, but it might be a good 
starting point.

Slava

> On Nov 3, 2017, at 7:01 PM, C. Keith Ray  wrote:
> 
> um... how can I cast functions taking one argument to a "generic function 
> pointer" type?
> 
> typealias OneArgsFunction = (Any)->Any
> 
> func intToInt(_ i: Int) -> Int { return 4 }
> func floatToFloat(_ f: Float) -> Float { return 0.4 }
> 
> var function : OneArgsFunction = intToInt
> function = floatToFloat
> 
> error: f.playground:4:34: error: cannot convert value of type '(Int) -> Int' 
> to specified type 'OneArgsFunction' (aka '(Any) -> Any')
> var function : OneArgsFunction = intToInt
>  ^~~~
> 
> error: f.playground:5:12: error: cannot assign value of type '(Float) -> 
> Float' to type 'OneArgsFunction' (aka '(Any) -> Any')
> function = floatToFloat
>^~~~
> 
> 
> --
> C. Keith Ray
> Senior Software Engineer / Trainer / Agile Coach
> * http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf 
> 
> 
> 
> 
>> On Nov 3, 2017, at 2:24 PM, Slava Pestov > > wrote:
>> 
>> Unfortunately we don’t have a way to invoke a function with a runtime 
>> argument list because that would require runtime code generation in the most 
>> general case.
>> 
>> I would hack around it by handling the common cases of no arguments, 1 
>> argument, 2 arguments, etc up to some fixed number of arguments that you 
>> consider “enough”. Use a switch on the type of the function.
>> 
>> Slava
>> 
>>> On Nov 3, 2017, at 2:21 PM, C. Keith Ray via swift-users 
>>> > wrote:
>>> 
>>> In the code below, I'm trying to store a reference to a function with any 
>>> number of arguments, with any return type. And I want to be able to invoke 
>>> it. 
>>> 
>>> Help?
>>> 
>>> See the comments with "***"
>>> 
>>> typealias Void = ()
>>> 
>>> func equalTypes(_ me: [Any.Type], _ other: [Any.Type]) -> Bool {
>>> guard me.count == other.count else { return false }
>>> 
>>> for i in 0 ..< me.count {
>>> if me[i] != other[i] { return false }
>>> }
>>> return true
>>> }
>>> 
>>> struct Function {
>>> var returnType: Any.Type
>>> var argTypes: [Any.Type]
>>> var function: Any // *** any function ***
>>> 
>>> func perform(_ args: [Any]) -> Any {
>>> // *** call function() with args, return result ***
>>> return 0
>>> }
>>> 
>>> func isCompatible(_ other: Function) -> Bool {
>>> return self.returnType == other.returnType &&
>>> equalTypes(argTypes, other.argTypes)
>>> }
>>> }
>>> 
>>> func vToV() {
>>> print("vToV")
>>> }
>>> 
>>> func intToInt(_ i: Int) -> Int {
>>> print("intToInt")
>>> return 4
>>> }
>>> 
>>> let f = Function(returnType: Void.self,
>>>  argTypes: [],
>>>  function: vToV)
>>> let r = f.perform([])
>>> print(r)
>>> 
>>> let f2 = Function(returnType: Int.self,
>>>  argTypes: [Int.self],
>>>  function: intToInt)
>>> let r2 = f2.perform([12])
>>> print(r2)
>>> 
>>> assert(f.isCompatible(f))
>>> assert(!f.isCompatible(f2))
>>> 
>>> 
>>> --
>>> C. Keith Ray
>>> Senior Software Engineer / Trainer / Agile Coach
>>> * http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf 
>>> 
>>> 
>>> 
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> 
> 

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


Re: [swift-users] How to store ref to any kind of function, and call with it argument list?

2017-11-03 Thread Slava Pestov via swift-users
Unfortunately we don’t have a way to invoke a function with a runtime argument 
list because that would require runtime code generation in the most general 
case.

I would hack around it by handling the common cases of no arguments, 1 
argument, 2 arguments, etc up to some fixed number of arguments that you 
consider “enough”. Use a switch on the type of the function.

Slava

> On Nov 3, 2017, at 2:21 PM, C. Keith Ray via swift-users 
>  wrote:
> 
> In the code below, I'm trying to store a reference to a function with any 
> number of arguments, with any return type. And I want to be able to invoke 
> it. 
> 
> Help?
> 
> See the comments with "***"
> 
> typealias Void = ()
> 
> func equalTypes(_ me: [Any.Type], _ other: [Any.Type]) -> Bool {
> guard me.count == other.count else { return false }
> 
> for i in 0 ..< me.count {
> if me[i] != other[i] { return false }
> }
> return true
> }
> 
> struct Function {
> var returnType: Any.Type
> var argTypes: [Any.Type]
> var function: Any // *** any function ***
> 
> func perform(_ args: [Any]) -> Any {
> // *** call function() with args, return result ***
> return 0
> }
> 
> func isCompatible(_ other: Function) -> Bool {
> return self.returnType == other.returnType &&
> equalTypes(argTypes, other.argTypes)
> }
> }
> 
> func vToV() {
> print("vToV")
> }
> 
> func intToInt(_ i: Int) -> Int {
> print("intToInt")
> return 4
> }
> 
> let f = Function(returnType: Void.self,
>  argTypes: [],
>  function: vToV)
> let r = f.perform([])
> print(r)
> 
> let f2 = Function(returnType: Int.self,
>  argTypes: [Int.self],
>  function: intToInt)
> let r2 = f2.perform([12])
> print(r2)
> 
> assert(f.isCompatible(f))
> assert(!f.isCompatible(f2))
> 
> 
> --
> C. Keith Ray
> Senior Software Engineer / Trainer / Agile Coach
> * http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf 
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Redundant superclass constraint

2017-10-25 Thread Slava Pestov via swift-users
Hi Phil,

I think the warning is bogus in this case. Do you mind filing a bug?

Slava

> On Oct 24, 2017, at 11:00 PM, Phil Kirby via swift-users 
>  wrote:
> 
> Original StackOverflow post:
> 
> https://stackoverflow.com/questions/46924554/redundant-superclass-constraint-in-swift-4
>  
> 
> 
>  
> 
>
> I'm getting a Redundant superclass constraint... warning in swift4: (paste in 
> a playground)
> 
> import CoreData
> 
> class Item : NSManagedObject {}
> 
> protocol DataSourceProtocol {
> associatedtype DataSourceItem : NSManagedObject
> }
> 
> protocol DataSourceProtocolProvider : class { }
> 
> extension DataSourceProtocolProvider {
> func createDataSource(dataSource: T)  
>  where T.DataSourceItem == Item {
> }
> }
> On the createDataSource declaration I get the 
> following warning:
> 
> Redundant superclass constraint 'T.DataSourceItem' : 'NSManagedObject'
> 
> I thought that you could specify that an associatedtype could be used with 
> the == operator to constrain the associatedtype to a specific type. I want to 
> have a func createDataSource(dataSource:T) where the 
> DataSourceItem is an Item.
> 
> If I replace the == operator with : then the warning goes away:
> 
> extension DataSourceProtocolProvider {
> func createDataSource(dataSource: T)  
>  where T.DataSourceItem : Item {
> }
> }
> This happens to be a completely different context now. This constraint 
> specifies that I want to have a func createDataSource DataSourceProtocol>(dataSource:T) where the DataSourceItem is a subclass of 
> Item. Which isn't the same thing as DataSourceItem is an Item object. Also, 
> the code runs fine with == so am I just not understanding how constraints 
> work?
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Expression was too complex to be solved in reasonable time

2017-10-24 Thread Slava Pestov via swift-users


> On Oct 24, 2017, at 3:05 PM, Nate Birkholz via swift-users 
>  wrote:
> 
> Doing a tutorial from RayWenderlich. 
> https://www.raywenderlich.com/125313/make-game-like-candy-crush-spritekit-swift-part-4
>  
> 
> 
> I have four bool values: topLeft, bottomLeft, topRight, and bottomRight
> 
> the following line throws an error: 
> let value = Int(topLeft.hashValue) | Int(topRight.hashValue) << 1 | 
> Int(bottomLeft.hashValue) << 2 | Int(bottomRight.hashValue) << 3

yeah,

let value1 = Int(topRight.hashValue) << 1
let value2 = Int(bottomLeft.hashValue) << 2
let value3 = Int(bottomRight.hashValue) << 3

let value = Int(topLeft.hashValue) | value1 | value2 | value3

> 
> "Expression was too complex to be solved in reasonable time; consider 
> breaking up the expression into distinct sub-expressions."
> 
> This seems like a bug in the compiler, no? Is there actually a way to break 
> that up? 

This is a known issue that got worse with the new integer oriented protocols, 
especially with shifts.

Slava

> 
> -- 
> Nate Birkholz
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] [Feature Request] Extend the `defer` statement

2017-10-08 Thread Slava Pestov via swift-users
I think you can achieve what you want by having the ‘defer’ block capture a 
mutable local variable. Eg,

func doStuff() {
  var success = false

  defer {
if !success {
  // do some additional cleanup
}
  }

  …
  success = true
  …

  return result
}

> On Oct 8, 2017, at 7:34 PM, Jun Zhang via swift-users  
> wrote:
> 
> Hi dear swift developers,
>I am kind of new to swift and I don't know if this feature already exists. 
> And if it exists already please tell me how. Thank you very much!
>   The feature is to capturing the return value (maybe input value also) of 
> the function. Here is the demo code:
> 
> func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
> Int) -> Int {
> defer {
> if $> >= 0 {
> // table is not empty
> }
> else {
> // table is empty
> }
> }
> return dataSource.cout
> }
> 
>I suggest using `$>` as the return value symbol and `$<` as the input 
> parameter symbol. 
>Thank you all and best regards to you!
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] How to check the type of a concrete class that inherits from a generic class?

2017-10-07 Thread Slava Pestov via swift-users
You can try upcasting the value to NSObject first, and then performing a 
conditional downcast to Controller1 and Controller2. At this point the type 
checker will not have enough information to decide that the cast always fails, 
and should no longer emit a warning.

Slava

> On Oct 6, 2017, at 11:55 PM, Glen Huang  wrote:
> 
> Done, https://bugs.swift.org/browse/SR-6083 
> 
> 
> In the mean time, is there any workaround? Or it’s not possible to check the 
> concrete type without this issue being fixed?
> 
>> On 7 Oct 2017, at 2:44 PM, Slava Pestov > > wrote:
>> 
>> Oh I see. I think the problem is that with Objective-C generics, you can 
>> always cast from Foo to Foo, because the type parameters do not really 
>> exist. Swift’s type checking logic for casts assumes Swift generic 
>> semantics, where in general Foo and Foo are unrelated types.
>> 
>> Do you mind filing a bug?
>> 
>> Slava
>> 
>>> On Oct 6, 2017, at 11:40 PM, Glen Huang >> > wrote:
>>> 
>>> NSFetchedResultsController is the class from Core Data: 
>>> 
>>> https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller
>>>  
>>> 
>>> 
 On 7 Oct 2017, at 2:38 PM, Slava Pestov  wrote:
 
 Can you post a self-contained example, including the declaration of 
 NSFetchedResultsController?
 
 Slava
 
> On Oct 6, 2017, at 11:28 PM, Glen Huang via swift-users 
>  wrote:
> 
> Hi,
> 
> I defined some concrete classes inheriting from a generic class like this:
> 
> class Controller1: NSFetchedResultsController {}
> class Controller2: NSFetchedResultsController {}
> 
> And I assign them a shared delegate, and in the delegate method:
> 
> func controllerWillChangeContent(_ controller: 
> NSFetchedResultsController)
> 
> I want to test the concrete type of controller, doing things differently 
> for Controller1 and Controller2.
> 
> But doing the following gives me a warning: Cast from 
> 'NSFetchedResultsController' to unrelated type 
> 'Controller1’ always fails
> 
> switch controller {
> case is Controller1:
> // ...
> default:
> break
> }
> 
> I wonder what’s the correct way to check the concrete type?
> 
> Regards,
> Glen
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
 
>>> 
>> 
> 

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


Re: [swift-users] How to check the type of a concrete class that inherits from a generic class?

2017-10-07 Thread Slava Pestov via swift-users
Oh I see. I think the problem is that with Objective-C generics, you can always 
cast from Foo to Foo, because the type parameters do not really exist. 
Swift’s type checking logic for casts assumes Swift generic semantics, where in 
general Foo and Foo are unrelated types.

Do you mind filing a bug?

Slava

> On Oct 6, 2017, at 11:40 PM, Glen Huang  wrote:
> 
> NSFetchedResultsController is the class from Core Data: 
> 
> https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller
> 
>> On 7 Oct 2017, at 2:38 PM, Slava Pestov  wrote:
>> 
>> Can you post a self-contained example, including the declaration of 
>> NSFetchedResultsController?
>> 
>> Slava
>> 
>>> On Oct 6, 2017, at 11:28 PM, Glen Huang via swift-users 
>>>  wrote:
>>> 
>>> Hi,
>>> 
>>> I defined some concrete classes inheriting from a generic class like this:
>>> 
>>> class Controller1: NSFetchedResultsController {}
>>> class Controller2: NSFetchedResultsController {}
>>> 
>>> And I assign them a shared delegate, and in the delegate method:
>>> 
>>> func controllerWillChangeContent(_ controller: 
>>> NSFetchedResultsController)
>>> 
>>> I want to test the concrete type of controller, doing things differently 
>>> for Controller1 and Controller2.
>>> 
>>> But doing the following gives me a warning: Cast from 
>>> 'NSFetchedResultsController' to unrelated type 
>>> 'Controller1’ always fails
>>> 
>>> switch controller {
>>> case is Controller1:
>>>  // ...
>>> default:
>>>  break
>>> }
>>> 
>>> I wonder what’s the correct way to check the concrete type?
>>> 
>>> Regards,
>>> Glen
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-users
>> 
> 

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


Re: [swift-users] How to check the type of a concrete class that inherits from a generic class?

2017-10-07 Thread Slava Pestov via swift-users
Can you post a self-contained example, including the declaration of 
NSFetchedResultsController?

Slava

> On Oct 6, 2017, at 11:28 PM, Glen Huang via swift-users 
>  wrote:
> 
> Hi,
> 
> I defined some concrete classes inheriting from a generic class like this:
> 
> class Controller1: NSFetchedResultsController {}
> class Controller2: NSFetchedResultsController {}
> 
> And I assign them a shared delegate, and in the delegate method:
> 
> func controllerWillChangeContent(_ controller: 
> NSFetchedResultsController)
> 
> I want to test the concrete type of controller, doing things differently for 
> Controller1 and Controller2.
> 
> But doing the following gives me a warning: Cast from 
> 'NSFetchedResultsController' to unrelated type 
> 'Controller1’ always fails
> 
> switch controller {
> case is Controller1:
>// ...
> default:
>break
> }
> 
> I wonder what’s the correct way to check the concrete type?
> 
> Regards,
> Glen
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] How to resolve "type(of: instance)" being shadowed by "instance.type"?

2017-09-22 Thread Slava Pestov via swift-users

> On Sep 22, 2017, at 10:10 PM, Glen Huang via swift-users 
>  wrote:
> 
> I have a class like this:
> 
> class File {
>   type: FileType
>   url: URL
>   func fetch(from server: Server) {
>   type(of: server).get(from: url)
>   }
> }
> 
> However, it fails to compile with "Cannot call value of non-function type 
> ‘File’” inside the body of fetch(from:). I believe the reason is that 
> self.type shadows  type(of: server).
> 
> Other than renaming the “type” property, is there any other way to work 
> around it? I tried "Foundation.type(of: server)” and found out that it’s from 
> the standard library and not Foundation. Is there a prefix that denotes the 
> standard library?

The standard library module is named ‘Swift’, so ‘Swift.type(of:)’ should do 
the trick.

> 
> A more general question, since this is clearly a function call, why would it 
> be shadowed by self.type, which is clearly a property access?
> 
> I’m using Swift 4 in Xcode 9.
> 
> Regards,
> Glen
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Can't implement generic subscript in protocol

2017-09-15 Thread Slava Pestov via swift-users

> On Sep 15, 2017, at 4:26 PM, Slava Pestov  wrote:
> 
> 
>> On Sep 15, 2017, at 12:40 PM, Joanna Carter via swift-users 
>>  wrote:
>> 
>> Xcode Version 9.0 (9A235)
>> 
>> Hmmm. I'm now getting a segmentation fault : 11 on a constructor when trying 
>> to implement type erasure :
> 
> Swift 4.0 had issues with members and member references named ‘subscript’. On 
> master, I get the correct error message without crashing:
> 
> Slavas-MBP:swift slava$ 
> ../build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin/swiftc sub.swift 
> sub.swift:22:17: error: value of type 'providerType' has no member 'subscript'
>   _subscript = base.subscript
>^~~~ ~
> 
> Indeed you’re not supposed to be able to refer to a subscript member like 
> this. You could use a keypath, or try some other approach.

You could also write an explicit closure that loads the subscript:

let fn = { base[$0] }

Slava

> 
> Slava
> 
>> 
>> protocol DataProvider
>> {
>> associatedtype ItemType
>> 
>> subscript(index: Int) -> ItemType { get }
>> }
>> 
>> class _AnyDataProviderBoxBase: DataProvider
>> {
>> subscript(index: Int) -> itemType
>> {
>>   fatalError()
>> }
>> }
>> 
>> class _AnyDataProviderBox: 
>> _AnyDataProviderBoxBase
>> {
>> private let _subscript: (_ index: Int) -> providerType.ItemType
>> 
>> init(_ base: providerType) // segmentation fault : 11
>> {
>>   _subscript = base.subscript
>> }
>> 
>> override subscript(index: Int) -> providerType.ItemType
>> {
>>   return _subscript(index)
>> }
>> }
>> 
>> final class AnyDataProvider: DataProvider
>> {
>> private let box: _AnyDataProviderBox
>> 
>> init(_ base: providerType)
>> {
>>   self.box = _AnyDataProviderBox(base)
>> }
>> 
>> subscript(index: Int) -> providerType.ItemType
>> {
>>   return box[index]
>> }
>> }
>> 
>> Joanna
>> 
>> --
>> Joanna Carter
>> Carter Consulting
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

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


Re: [swift-users] Can't implement generic subscript in protocol

2017-09-15 Thread Slava Pestov via swift-users

> On Sep 15, 2017, at 12:40 PM, Joanna Carter via swift-users 
>  wrote:
> 
> Xcode Version 9.0 (9A235)
> 
> Hmmm. I'm now getting a segmentation fault : 11 on a constructor when trying 
> to implement type erasure :

Swift 4.0 had issues with members and member references named ‘subscript’. On 
master, I get the correct error message without crashing:

Slavas-MBP:swift slava$ 
../build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin/swiftc sub.swift 
sub.swift:22:17: error: value of type 'providerType' has no member 'subscript'
   _subscript = base.subscript
^~~~ ~

Indeed you’re not supposed to be able to refer to a subscript member like this. 
You could use a keypath, or try some other approach.

Slava

> 
> protocol DataProvider
> {
>  associatedtype ItemType
> 
>  subscript(index: Int) -> ItemType { get }
> }
> 
> class _AnyDataProviderBoxBase: DataProvider
> {
>  subscript(index: Int) -> itemType
>  {
>fatalError()
>  }
> }
> 
> class _AnyDataProviderBox: 
> _AnyDataProviderBoxBase
> {
>  private let _subscript: (_ index: Int) -> providerType.ItemType
> 
>  init(_ base: providerType) // segmentation fault : 11
>  {
>_subscript = base.subscript
>  }
> 
>  override subscript(index: Int) -> providerType.ItemType
>  {
>return _subscript(index)
>  }
> }
> 
> final class AnyDataProvider: DataProvider
> {
>  private let box: _AnyDataProviderBox
> 
>  init(_ base: providerType)
>  {
>self.box = _AnyDataProviderBox(base)
>  }
> 
>  subscript(index: Int) -> providerType.ItemType
>  {
>return box[index]
>  }
> }
> 
> Joanna
> 
> --
> Joanna Carter
> Carter Consulting
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Can't implement generic subscript in protocol

2017-09-15 Thread Slava Pestov via swift-users

> On Sep 15, 2017, at 12:40 PM, Joanna Carter via swift-users 
>  wrote:
> 
> Greetings
> 
> Now we've got generic subscripts, I thought I'd play…
> 
> protocol DataProvider
> {
>  subscript(index: Int) -> itemType { get }
> }

This is a valid usage of your protocol:

func doesStuff(p: DataProvider) {
  let i: Int = p[0]
  let s: String = p[1]
}

> 
> class Test : DataProvider // error : Type 'Test' does not conform to protocol 
> 'DataProvider'
> {
>  subscript(index: Int) -> String
>  {
>return "Fred"
>  }
> }
> 
> Simple questions:
> 
> 1. why does this not compile?

Imagine if I pass an instance of class Test to my function doesStuff() above. 
What would the first line of code do, given that it’s expecting to get back an 
Int result but the subscript in the class always returns a String?


> 2. should it?
> 3. is there a workaround without declaring an associated type in the protocol?

Either the protocol should have a non-generic subscript, or the class should 
have a generic subscript. Note that the same would happen if you do something 
like

protocol P {
  func f() -> T
}

class C : P {
  func f() -> String
}

Again, here C.f is ‘too concrete’.

Slava

> 
> Joanna
> 
> --
> Joanna Carter
> Carter Consulting
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Can you use @autoclosure in a setter?

2017-09-11 Thread Slava Pestov via swift-users
Oh I see, the property itself does not have autoclosure type.

Slava

> On Sep 11, 2017, at 3:52 PM, Slava Pestov <spes...@apple.com> wrote:
> 
> No, newValue is a closure here, and valueSource will capture this closure. 
> When valueSource is evaluated, the original closure will be evaluated.
> 
> Slava
> 
>> On Sep 11, 2017, at 3:11 PM, Hooman Mehr <hoo...@mac.com 
>> <mailto:hoo...@mac.com>> wrote:
>> 
>> But the expression that is assigned to the property will be eagerly 
>> evaluated to produce `newValue`. So this will not accomplish what Nevin is 
>> trying to do. 
>> 
>>> On Sep 11, 2017, at 3:08 PM, Slava Pestov via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> You can have valueSource store a closure that captures the autoclosure 
>>> value. For example,
>>> 
>>> set {
>>>   valueSource = { newValue }
>>> }
>>> 
>>> Slava
>>> 
>>>> On Sep 11, 2017, at 11:04 AM, Nevin Brackett-Rozinsky via swift-users 
>>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>>> 
>>>> Hi, quick question here:
>>>> 
>>>> I have a class with a property that needs to be really *really* lazy. So 
>>>> lazy, in fact, that when you assign to that property, the class actually 
>>>> stores a closure of what you assigned, which is only evaluated if and when 
>>>> you actually attempt to read the property.
>>>> 
>>>> Simplified:
>>>> 
>>>> class Foo {
>>>>   private var valueSource: () -> Bar
>>>>   private var valueCache: Bar?
>>>>   
>>>>   init(_ v: @escaping @autoclosure () -> Bar) {
>>>> valueSource = v
>>>>   }
>>>>   
>>>>   var value: Bar {
>>>> get {
>>>>   if let v = valueCache { return v }
>>>>   let w = valueSource()
>>>>   valueCache = w
>>>>   return w
>>>> }
>>>> set {
>>>>   /* ??? */
>>>> }
>>>>   }
>>>>   
>>>>   // I want this function's logic to go in the setter above
>>>>   func setValue(_ v: @escaping @autoclosure () -> Bar) {
>>>> valueSource = v
>>>> valueCache = nil
>>>>   }
>>>> }
>>>> 
>>>> The goal is to be able to write things like “someFoo.value = bar1 / bar2” 
>>>> (or even more complex expressions) and not evaluate them until/unless the 
>>>> result is actually needed.
>>>> 
>>>> Currently I am using “someFoo.setValue( bar1 / bar2 )”, which is not 
>>>> nearly as ergonomic as the assignment syntax. So, is there a way to make 
>>>> this work?
>>>> 
>>>> Nevin
>>>> ___
>>>> swift-users mailing list
>>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>> 
> 

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


Re: [swift-users] Can you use @autoclosure in a setter?

2017-09-11 Thread Slava Pestov via swift-users
No, newValue is a closure here, and valueSource will capture this closure. When 
valueSource is evaluated, the original closure will be evaluated.

Slava

> On Sep 11, 2017, at 3:11 PM, Hooman Mehr <hoo...@mac.com> wrote:
> 
> But the expression that is assigned to the property will be eagerly evaluated 
> to produce `newValue`. So this will not accomplish what Nevin is trying to 
> do. 
> 
>> On Sep 11, 2017, at 3:08 PM, Slava Pestov via swift-users 
>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>> 
>> You can have valueSource store a closure that captures the autoclosure 
>> value. For example,
>> 
>> set {
>>   valueSource = { newValue }
>> }
>> 
>> Slava
>> 
>>> On Sep 11, 2017, at 11:04 AM, Nevin Brackett-Rozinsky via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> Hi, quick question here:
>>> 
>>> I have a class with a property that needs to be really *really* lazy. So 
>>> lazy, in fact, that when you assign to that property, the class actually 
>>> stores a closure of what you assigned, which is only evaluated if and when 
>>> you actually attempt to read the property.
>>> 
>>> Simplified:
>>> 
>>> class Foo {
>>>   private var valueSource: () -> Bar
>>>   private var valueCache: Bar?
>>>   
>>>   init(_ v: @escaping @autoclosure () -> Bar) {
>>> valueSource = v
>>>   }
>>>   
>>>   var value: Bar {
>>> get {
>>>   if let v = valueCache { return v }
>>>   let w = valueSource()
>>>   valueCache = w
>>>   return w
>>> }
>>> set {
>>>   /* ??? */
>>> }
>>>   }
>>>   
>>>   // I want this function's logic to go in the setter above
>>>   func setValue(_ v: @escaping @autoclosure () -> Bar) {
>>> valueSource = v
>>> valueCache = nil
>>>   }
>>> }
>>> 
>>> The goal is to be able to write things like “someFoo.value = bar1 / bar2” 
>>> (or even more complex expressions) and not evaluate them until/unless the 
>>> result is actually needed.
>>> 
>>> Currently I am using “someFoo.setValue( bar1 / bar2 )”, which is not nearly 
>>> as ergonomic as the assignment syntax. So, is there a way to make this work?
>>> 
>>> Nevin
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto:swift-users@swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

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


Re: [swift-users] Can you use @autoclosure in a setter?

2017-09-11 Thread Slava Pestov via swift-users
You can have valueSource store a closure that captures the autoclosure value. 
For example,

set {
  valueSource = { newValue }
}

Slava

> On Sep 11, 2017, at 11:04 AM, Nevin Brackett-Rozinsky via swift-users 
>  wrote:
> 
> Hi, quick question here:
> 
> I have a class with a property that needs to be really *really* lazy. So 
> lazy, in fact, that when you assign to that property, the class actually 
> stores a closure of what you assigned, which is only evaluated if and when 
> you actually attempt to read the property.
> 
> Simplified:
> 
> class Foo {
>   private var valueSource: () -> Bar
>   private var valueCache: Bar?
>   
>   init(_ v: @escaping @autoclosure () -> Bar) {
> valueSource = v
>   }
>   
>   var value: Bar {
> get {
>   if let v = valueCache { return v }
>   let w = valueSource()
>   valueCache = w
>   return w
> }
> set {
>   /* ??? */
> }
>   }
>   
>   // I want this function's logic to go in the setter above
>   func setValue(_ v: @escaping @autoclosure () -> Bar) {
> valueSource = v
> valueCache = nil
>   }
> }
> 
> The goal is to be able to write things like “someFoo.value = bar1 / bar2” (or 
> even more complex expressions) and not evaluate them until/unless the result 
> is actually needed.
> 
> Currently I am using “someFoo.setValue( bar1 / bar2 )”, which is not nearly 
> as ergonomic as the assignment syntax. So, is there a way to make this work?
> 
> Nevin
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Type alias with a "where" clause specifying required associated type

2017-09-05 Thread Slava Pestov via swift-users
It’s just placeholder syntax for ‘a value whose type is given by a generic 
parameter in the following signature’.

Slava

> On Sep 5, 2017, at 4:44 AM, Rudolf Adamkovič  wrote:
> 
> I see. TBH, I don’t understand why it says “Any” in the "generalized 
> existentials” but everything else is clear. 
> 
> Thank you Slava!
> 
> R+
> 
>> On 5 Sep 2017, at 01:52, Slava Pestov > > wrote:
>> 
>> Hi Rudolf,
>> 
>> What you are describing is not possible right now. The protocol PointType 
>> cannot be used as a type at all, because it has an associated type 
>> requirement. Also it is not clear what a ‘where’ clause attached to a type 
>> alias would mean.
>> 
>> There has been some discussion of ‘generalized existentials’ on the 
>> evolution list. So eventually, you might be able to say something like this:
>> 
>> typealias Point = Any
>> 
>> Slava
>> 
>>> On Sep 4, 2017, at 6:12 PM, Rudolf Adamkovič via swift-users 
>>> > wrote:
>>> 
>>> I have the following ProceduralDrawing type:
>>> 
>>> public struct ProceduralDrawing where Point.Float 
>>> == Float {
>>> // ... code that used Float and Point ...
>>> }
>>> 
>>> public protocol PointType {
>>> associatedtype Float: FloatingPoint
>>> var x: Float { get }
>>> var y: Float { get }
>>> }
>>> 
>>> I would like to avoid adding Point as a generic parameter but the following 
>>> doesn’t work:
>>> 
>>> public struct ProceduralDrawing {
>>> // ERROR: 'where' clause cannot be attached to a non-generic declaration
>>> typealias Point = PointType where Point.Float == Float
>>> // ... code that uses Float and Point ...
>>> }
>>> 
>>> Is there a way to do this? If not, why?
>>> 
>>> Thanks!
>>> 
>>> R+
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> 
> 

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


Re: [swift-users] Is this a compiler bug?

2017-09-04 Thread Slava Pestov via swift-users
Yeah, looks like a bug. Do you mind filing a JIRA?

Slava

> On Sep 4, 2017, at 8:55 PM, Howard Lovatt via swift-users 
>  wrote:
> 
> Hi All,
> 
> Is this a compiler bug?
> 
> struct Box {
> var value: T
> init(_ value: T) { self.value = value }
> /// Unboxing operator.
> static func >> (left: Box, right: inout T?) {
> right = left.value
> }
> }
> 
> var u: String?
> let b = Box("Test")
> b >>  // ERROR: Cannot convert value of type 'Box' to expected 
> argument type 'Box<_>'
> Am I missing something?
> 
> Thanks in advance for any help,
> 
>   -- Howard.
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Type alias with a "where" clause specifying required associated type

2017-09-04 Thread Slava Pestov via swift-users
Hi Rudolf,

What you are describing is not possible right now. The protocol PointType 
cannot be used as a type at all, because it has an associated type requirement. 
Also it is not clear what a ‘where’ clause attached to a type alias would mean.

There has been some discussion of ‘generalized existentials’ on the evolution 
list. So eventually, you might be able to say something like this:

typealias Point = Any

Slava

> On Sep 4, 2017, at 6:12 PM, Rudolf Adamkovič via swift-users 
>  wrote:
> 
> I have the following ProceduralDrawing type:
> 
> public struct ProceduralDrawing where Point.Float == 
> Float {
> // ... code that used Float and Point ...
> }
> 
> public protocol PointType {
> associatedtype Float: FloatingPoint
> var x: Float { get }
> var y: Float { get }
> }
> 
> I would like to avoid adding Point as a generic parameter but the following 
> doesn’t work:
> 
> public struct ProceduralDrawing {
> // ERROR: 'where' clause cannot be attached to a non-generic declaration
> typealias Point = PointType where Point.Float == Float
> // ... code that uses Float and Point ...
> }
> 
> Is there a way to do this? If not, why?
> 
> Thanks!
> 
> R+
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Type of expression is ambiguous for static tuples

2017-09-01 Thread Slava Pestov via swift-users
Yeah, my understanding is that .foo syntax only works if ‘foo’ is an immediate 
static member of the contextual type where the expression appears. So nested 
member access like .foo.b ar does not make sense.

Slava

> On Sep 1, 2017, at 6:04 AM, Adrian Zubarev via swift-users 
>  wrote:
> 
> Yet this is correct behavior because the compiler cannot traverse the 
> expression tree without knowing the root type of that expression tree. The 
> type information flow in such case should be from root to the leaves where 
> the root is NOT the root of the expression, but the type from the function 
> parameter, which then should be passed to the expression tree. However the 
> expression tree is not complete, because there MIGHT be another 
> `phythagoreanTruple` somewhere else. Even if there is no other 
> `phythagoreanTruple`, here the general rules are applied which results into 
> the mentioned error message.
> 
> Please correct me if I’m wrong here.
> 
> 
> Am 1. September 2017 um 14:53:35, David Hart (da...@hartbit.com 
> ) schrieb:
> 
>> Its slightly different though. In the case of:
>> 
>> let cgColor: CGColor = .clear.cgColor
>> 
>> clear is a static property on UIColor, not CGColor. In his example, 
>> pythagoreanTriple is a property on Double so it does feel like a bug.
>> 
>>> On 1 Sep 2017, at 13:31, Adrian Zubarev via swift-users 
>>> > wrote:
>>> 
>>> It’s because the compiler does not support this yet. It’s the same with 
>>> `let cgColor: CGColor = .clear.cgColor // will not work`.
>>> 
>>> Instead you need to write `UIColor.clear.cgColor` or in your case 
>>> `Double.phythagoreanTruple.0`
>>> 
>>> 
>>> Am 1. September 2017 um 12:17:57, Rudolf Adamkovič via swift-users 
>>> (swift-users@swift.org ) schrieb:
>>> 
 Given the following extension ...
 
 extension Double {
 typealias Triple = (Double, Double, Double)
 static let pythagoreanTriple: Triple = (3, 4, 5)
 }
 ... why does Swift compiler emits the following errors?
 
 // Type of expression is ambiguous without more context
 let a: Double = .pythagoreanTriple.0
 
 // Type of expression is ambiguous without more context
 func f(_ x: Double) {}
 f(.pythagoreanTriple.0)
 The errors disappear with explicit Double.pythagoreanTriple.0.
 
 Why doesn't the compiler infer Double in this case?
 
 FYI: Posted also to Stack Overflow here:
 
 https://stackoverflow.com/questions/45998034/type-of-expression-is-ambiguous-for-static-tuples
  
 
 R+
 
 ___
 swift-users mailing list
 swift-users@swift.org 
 https://lists.swift.org/mailman/listinfo/swift-users
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Swift4/iOS question

2017-08-28 Thread Slava Pestov via swift-users

> On Aug 28, 2017, at 1:58 PM, Travis Griggs via swift-users 
>  wrote:
> 
> If I need to take this question elsewhere, please point me to the right list.
> 
> I decided to take the dive this morning and give XCode9 beta and Swift 4 a 
> try. I’m tired of not being able to refactor.
> 
> There are two things that the importer is trying to commonly change that I’m 
> curious about:
> 
> 1) Anywhere I’ve linked a UIControl to a method via the addTarget(self, 
> action: #selector(foobar), for: .valueChanged), it now feels that foobar 
> needs to be annotated as @objc. I really liked that so far in my swift 
> journey, I’ve never had to put one of these @objc things in. I think I get 
> what’s going on. My class is a swift class, but is a subclass from 
> UIViewController, an objc class. While apparently, it could infer that 
> subclass methods should be objc callable, they no longer are?

There was a change in Swift 4.0 to make @objc inference narrower in scope. See 
https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md
 

 for a description of the change and rationale.

> 
> What’s frustrating is that if UIControl just had an action API that used 
> closures instead of the older perform: patterns, I’d just rewrite these as 
> such. But it still doesn’t. So people still make extensions which have to 
> resort to static globals or associated_objects.
> 
> 2) I have a couple of CALayer subclasses that have a couple different ways of 
> setting/accessing the same thing. I use dynamic vars for those. Once upon a 
> time, someone told me that I needed to make them dynamic for the animation 
> engine to correctly note changes to them. Apparently, those all need to be 
> tagged @objc now. Which seems redundant to me. Are not dynamic vars already 
> implicitly objc anyway? Is the new need to add @objc just for consistency 
> sake?

This is also part of SE-0160. The reason dynamic no longer implies @objc is 
that one day we could make dynamic work independent of the Objective-C runtime, 
and support it on Linux too for instance.

Slava

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

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


Re: [swift-users] Where to download Swift v.3.2 for Linux?

2017-08-24 Thread Slava Pestov via swift-users
HI Mr Bee,

“Swift 3.2” refers to running the Swift 4.0 compiler with the -swift-version 3 
flag. It is not a separate download.

Slava

> On Aug 24, 2017, at 7:44 AM, Mr Bee via swift-users  
> wrote:
> 
> Hi all,
> 
> I'm now using Swift v.3.0 on Linux (ubuntu) and about preparing to migrate to 
> the new Swift v.4.0.
> 
> On https://swift.org/migration-guide-swift4/ 
>  it is said that:
> 
> "Make sure that the project that you intend to migrate builds successfully in 
> Swift 3.2 mode, and all its tests pass. Keep in mind that Swift 3.2 does have 
> significant changes from 3.1, as well as the SDKs against which you built, so 
> you may need to resolve errors initially."
> 
> But I couldn't find any references to Swift v.3.2 on the site. Where's the 
> Swift v.3.2 for Linux? Is this Swift 3.2 mode delivered along with Swift 
> v.4.0?
> 
> It also seems that Swift Migration Assistant is only available through Xcode. 
> Am I right? If it's so then Linux is still considered as second-class citizen 
> in Swift development. 
> 
> I hope someday Linux will get equal support as the Mac/iOS counterpart. 
> Because I think the backend side (on Linux) of Swift app is also as important 
> as the iOS front-end side.
> 
> Thank you.
> 
> -- 
> 
> Regards,
> 
> 
> –Mr Bee
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Question with calling a method which returns `Self` on super

2017-08-10 Thread Slava Pestov via swift-users

> On Aug 10, 2017, at 8:23 PM, Slava Pestov via swift-users 
> <swift-users@swift.org> wrote:
> 
> Hi Lincoln,
> 
> This is a known issue with ‘super’ method calls: 
> https://bugs.swift.org/browse/SR-1736 <https://bugs.swift.org/browse/SR-1736>
> 
> A workaround is to cast the result of the supermethod call to Self explicitly:
> 
> let copied = super.copy() as! Self

I’m sorry, but this is nonsense. We don’t allow ‘Self’ to refer to the dynamic 
Self type yet.

You could do something like this I guess,

func cast<T, U>(from: T, to: U.Type) -> U {
  return from as! U
}

let copied = cast(from: super.copy(), to: type(of: self))

Slava

> 
> Slava
> 
>> On Aug 10, 2017, at 8:16 PM, 吴君恺 via swift-users <swift-users@swift.org 
>> <mailto:swift-users@swift.org>> wrote:
>> 
>> Hi all,
>> 
>> here is the scenario, I want to implement a Copying protocol which can be 
>> used homogeneously
>> 
>> protocol Copying {
>> func copy() -> Self
>> }
>> 
>> Because this protocol contains neither associated-type-requirements or 
>> self-requirements(requiring a method returning Self is different), it can 
>> surely be used homogeneously.
>> 
>> let objects: [Copying] = 
>> for copyable in objects {
>> .
>> }
>> 
>> It will work if I make one of my base class conform to Copying
>> 
>> class Shape: Copying {
>> var color: UIColor?
>> 
>> required init() {}
>> 
>> func copy() -> Self {
>> let copied = type(of: self).init()
>> copied.color = color
>> return copied
>> }
>> }
>> 
>> The implementation of `copy` above is forced by compiler to avoid any 
>> explicit specification of type `Shape`, so that the returning value will 
>> have a dynamic type, which is just what I want. Here, the type of `copied` 
>> is `Self`
>> 
>> However, if I try to make a subclass of Shape, I can't find a elegant way to 
>> implement this `copy` method in that subclass, the following code will not 
>> compile.
>> 
>> class Circle: Shape {
>> var radius: Float = 5
>> 
>> func copy() -> Self {
>> let copied = super.copy() 
>> copied.radius = radius // compilation error
>> return copied
>> }
>> }
>> 
>> The compiler will complain that `copied` has no property `radius`. It turns 
>> out that calling copy() on super will yield a value of type Shape, rather 
>> than Self. 
>> 
>> Swift now forbids explicit conversion to `Self` (I totally agree with this 
>> rule), and will automatically allow `Self` to be treated as a specific type 
>> in some circumstances. But for this case, I wonder whether this is the 
>> correct behavior or a bug? Why calling `super.copy()` not be able to get a 
>> `Self`?
>> 
>> I did find a work-around for this problem afterwards, but this question 
>> really haunts me...
>> 
>> Cheers,
>> Lincoln.
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto:swift-users@swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Question with calling a method which returns `Self` on super

2017-08-10 Thread Slava Pestov via swift-users
Hi Lincoln,

This is a known issue with ‘super’ method calls: 
https://bugs.swift.org/browse/SR-1736 

A workaround is to cast the result of the supermethod call to Self explicitly:

let copied = super.copy() as! Self

Slava

> On Aug 10, 2017, at 8:16 PM, 吴君恺 via swift-users  
> wrote:
> 
> Hi all,
> 
> here is the scenario, I want to implement a Copying protocol which can be 
> used homogeneously
> 
> protocol Copying {
> func copy() -> Self
> }
> 
> Because this protocol contains neither associated-type-requirements or 
> self-requirements(requiring a method returning Self is different), it can 
> surely be used homogeneously.
> 
> let objects: [Copying] = 
> for copyable in objects {
> .
> }
> 
> It will work if I make one of my base class conform to Copying
> 
> class Shape: Copying {
> var color: UIColor?
> 
> required init() {}
> 
> func copy() -> Self {
> let copied = type(of: self).init()
> copied.color = color
> return copied
> }
> }
> 
> The implementation of `copy` above is forced by compiler to avoid any 
> explicit specification of type `Shape`, so that the returning value will have 
> a dynamic type, which is just what I want. Here, the type of `copied` is 
> `Self`
> 
> However, if I try to make a subclass of Shape, I can't find a elegant way to 
> implement this `copy` method in that subclass, the following code will not 
> compile.
> 
> class Circle: Shape {
> var radius: Float = 5
> 
> func copy() -> Self {
> let copied = super.copy() 
> copied.radius = radius // compilation error
> return copied
> }
> }
> 
> The compiler will complain that `copied` has no property `radius`. It turns 
> out that calling copy() on super will yield a value of type Shape, rather 
> than Self. 
> 
> Swift now forbids explicit conversion to `Self` (I totally agree with this 
> rule), and will automatically allow `Self` to be treated as a specific type 
> in some circumstances. But for this case, I wonder whether this is the 
> correct behavior or a bug? Why calling `super.copy()` not be able to get a 
> `Self`?
> 
> I did find a work-around for this problem afterwards, but this question 
> really haunts me...
> 
> Cheers,
> Lincoln.
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] @_transparent allowing a data member inside an enum inside MemoryLayout.swift

2017-08-02 Thread Slava Pestov via swift-users

> On Aug 2, 2017, at 4:01 PM, Shyamal Chandra via swift-users 
>  wrote:
> 
> Hi,
> 
> After reading the Ray Wenderlich website tutorial [1] about Unsafe Swift, I 
> was checking out this file [3] inside swift/stdlib/public/core titled 
> MemoryLayout.swift.  However, I was confused about the @_transparent before 
> the each data member inside the enum.  Why is this enum with the data members 
> allowed by the Swift 3 language?  What does @_transparent allow you to do 
> that you might not otherwise?  Could someone explain because the 
> documentation is still unclear [2]?

@_transparent is only meant for use by the standard library and overlays. 
However, I’d be happy to answer any questions you may have about this attribute 
or its implementation, however you’ll need to be more specific. Which parts of 
TransparentAttr.rst are unclear? Note that the document is somewhat outdated 
but still largely accurate (some of the individual problems listed at the end 
have since been fixed, but the overall issues remain).

Slava

> 
> Thanks!
> 
> Best,
> 
> Shyamal Chandra
> shyam...@gmail.com 
> 
> Sources:
> 
> [1] https://www.raywenderlich.com/148569/unsafe-swift 
> 
> [2] https://github.com/apple/swift/blob/master/docs/TransparentAttr.rst 
> 
> [3] 
> https://github.com/apple/swift/blob/master/stdlib/public/core/MemoryLayout.swift
>  
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Constraining the conforming type of a protocol

2017-07-29 Thread Slava Pestov via swift-users
What you’re trying to do should be equivalent to this:

protocol Toggling : Equatable {
  …
}

It’s a bug that placing the constraint on ‘Self’ does not have the same effect 
though; do you mind filing a JIRA?

Slava

> On Jul 29, 2017, at 12:24 PM, Ray Fix via swift-users  
> wrote:
> 
> Hi,
> 
> I had a question about defining protocols. Originally I wrote:
> 
> protocol Toggling where Self: Equatable {
>   static var all: [Self] { get }
>   func toggled() -> Self
>   mutating func toggle()
> }
> 
> extension Toggling {
> 
>   func toggled() -> Self {
> let current = Self.all.index(of: self) ?? 0
> let next = (current + 1) % Self.all.count
> return Self.all[next]
>   }
> 
>   mutating func toggle() {
> self = toggled()
>   }
> }
> 
> This resulted in a bunch of errors.  
> 
> Playground execution failed:
>  ^
> error: Toggler.playground:7:28: error: cannot invoke 'index' with an argument 
> list of type '(of: Self)'
> let current = Self.all.index(of: self) ?? 0
>^
> 
> Toggler.playground:7:28: note: expected an argument list of type '(of: 
> Self.Element)'
> let current = Self.all.index(of: self) ?? 0
> 
> This approach worked:
> 
> 
> protocol Toggling {
>   static var all: [Self] { get }
>   func toggled() -> Self
>   mutating func toggle()
> }
> 
> extension Toggling where Self: Equatable {
> 
>   func toggled() -> Self {
> let current = Self.all.index(of: self) ?? 0
> let next = (current + 1) % Self.all.count
> return Self.all[next]
>   }
> 
>   mutating func toggle() {
> self = toggled()
>   }
> }
> 
> This version is probably better anyway but I am wondering if the first 
> approach should have shown an error at the point of trying to attach the 
> constraint to the protocol declaration.  Any insights on this?
> 
> Thank you,
> Ray  Fix
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] ⁨Is it possible to store a set of heterogeneous items with protocol?

2017-07-19 Thread Slava Pestov via swift-users
Hopefully we will one day have generalized existentials which would at least 
allow a heterogeneous array of protocols with an associated type; however it is 
not clear how such an existential could conform to Hashable in a general way, 
given that Hashable implies Equatable which has a Self requirement.

Slava

> On Jul 18, 2017, at 10:36 PM, Glen Huang via swift-users 
>  wrote:
> 
> Do you think if there will be any evolution proposal to address this 
> limitation? Or it’s an inherent tradeoff that is unlikely to be changed?
> 
>> On 19 Jul 2017, at 8:49 AM, Jordan Rose > > wrote:
>> 
>> 
>> 
>>> On Jul 18, 2017, at 10:33, Vladimir.S via swift-users 
>>> > wrote:
>>> 
>>> On 17.07.2017 4:51, Glen Huang via swift-users wrote:
 Thanks for the code sample and link, but if I’m not wrong, this pattern 
 doesn’t allow heterogeneous items.
>>> 
>>> Support the question. Trying to understand if we can have something like 
>>> [AnyHashable] for our custom protocol(with associated type) or AnyHashable 
>>> has a very special support from compiler and we can use only [Any] or such 
>>> kind of wrapper:
>>> 
>>> struct AnyMyProtocol {
>>>  let actualInstance: Any
>>>  init(_ instance: T) { actualInstance = instance}
>>> }
>>> 
>>> let instances: [AnyMyProtocol] = [AnyMyProtocol(...), AnyMyProtocol(...)]
>>> 
>>> if let some = instances[0].actualInstance as? 
>>> SpecificImplementationOfMyProtocol {
>>> // use 'some' as SpecificImplementationMyProtocol instance
>>> // seems like no way to refer to just MyProtocol
>>> }
>> 
>> AnyHashable is special, sorry. You'll have to use this sort of indirect 
>> unwrapping instead. You can write a little convenience method for it though, 
>> if you want:
>> 
>> extension AnyMyProtocol {
>>   func get(as: T.Type) -> T? {
>> return self.actualInstance as? T
>>   }
>> }
>> 
>> if let some = instances[0].get(as: SpecificImplementationOfMyProtocol.self) {
>>   // use 'some' here
>> }
>> 
>> Jordan
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Convenience initializers in structs?

2017-07-18 Thread Slava Pestov via swift-users
Hi Jens,

While I’m not familiar with the integer API in the standard library, structs 
and enums certainly can have convenience initializers. They must delegate to 
another initializer (either convenience or designated) rather than initializing 
the fields of the type one by one.

Slava

> On Jul 18, 2017, at 6:46 AM, Jens Persson via swift-users 
>  wrote:
> 
> Start a command line project in Xcode 9 beta 3 and copy paste this single 
> line of code into main.swift
> 
> let _ = UInt8.init(extendingOrTruncating: UInt64(123456))
> 
> Now look at Quick Help while placing the cursor on `init` and then on 
> `extendingOrTruncating`.
> 
> Note that (and how) the documentation for the initializer differs depending 
> on where you place the cursor.
> 
> If the cursor is on `init`, the initializer is shown to be a convenience(!) 
> initializer even though structs (such as UInt8) cannot have convenience 
> initializers, right?
> 
> Even the official documentation for this and several other initializer like 
> eg:
> https://developer.apple.com/documentation/swift/int/2885075-init 
> 
> clearly shows convenience initializers in structs.
> 
> By the way, .init(extendingOrTruncating:) doesn't show in the list of 
> completions for "UInt8.init" but it does for "UInt8(".
> 
> 
> Can anyone explain what's going on?
> 
> Are these known issues that will go away in time for Xcode 9 GM?
> 
> /Jens
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Printing Enums?

2017-07-17 Thread Slava Pestov via swift-users
There’s already a radar filed for this (I don’t know if there’s a JIRA bug 
though).

The problem is that the standard library’s reflection mechanism only knows how 
to map the in-memory representation of an enum to a case name for native Swift 
enums. Objective-C enums are represented by their ‘raw value’, and we don’t 
store the mapping in a way that’s accessible to the reflection code.

Slava

> On Jul 17, 2017, at 3:33 PM, Alex Blewitt via swift-users 
>  wrote:
> 
>> On 17 Jul 2017, at 15:15, Michael Rogers via swift-users 
>> > wrote:
>> 
>> Hi, All:
>> 
>> Can someone please enlighten me as to why the first enum works as expected, 
>> giving me Melbourne, but the second gives UIModalPresentationStyle rather 
>> than fullScreen?
> 
> Sure - it's because it's an alias that is imported via Objective-C rather 
> than defined in Swift:
> 
> typedef NS_ENUM(NSInteger, UIModalPresentationStyle) {
> UIModalPresentationFullScreen = 0,
> UIModalPresentationPageSheet NS_ENUM_AVAILABLE_IOS(3_2) 
> __TVOS_PROHIBITED,
> UIModalPresentationFormSheet NS_ENUM_AVAILABLE_IOS(3_2) 
> __TVOS_PROHIBITED,
> UIModalPresentationCurrentContext NS_ENUM_AVAILABLE_IOS(3_2),
> UIModalPresentationCustom NS_ENUM_AVAILABLE_IOS(7_0),
> 
> (you can see this in the UIViewController.h file in the UIKit, which is found 
> underneath your Xcode install)
> 
> The importer notes that the name of such typedef'd constants effectively 
> become translated into an enum as far as Swift source code is concerned, but 
> it's a different kind of case.
> 
> Having said that, it might be a bug in the case that the description of the 
> constant isn't the name of the element type. It would be worth raising this 
> on bugs.swift.org  and use this example in case 
> there's something that can be done to fix it.
> 
> Alex
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Is there any harm that an @escaping handler never called?

2017-07-11 Thread Slava Pestov via swift-users
No, there is no requirement to invoke a closure at least once, escaping or not.

Slava

> On Jul 11, 2017, at 3:55 PM, Zhao Xin via swift-users  
> wrote:
> 
> For example, I have an async query, I pass it an `@escaping resultHandler`. 
> If there is any results, the handler will run. However, if the result is 
> empty, the `@escaping resultHandler` will never run.
> 
> Is there any memory leak or something will happen if the `@escaping 
> resultHandler` never runs?
> 
> Zhao Xin
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] How to add this generic static func as a protocol requirement?

2017-07-07 Thread Slava Pestov via swift-users
Try using an associated type for the result of foo():

protocol P {
  associatedtype R

  static func foo(_ v: T) -> R
}

Slava

> On Jul 7, 2017, at 1:50 AM, Jens Persson via swift-users 
>  wrote:
> 
> protocol P {
> // …
> // For example the following will not work:
> // static func foo(_ v: T) -> R
> // Is there some other way?
> // …
> }
> struct S2 : P {
> static func foo(_ v: T) -> (T, T) {
> return (v, v)
> }
> }
> struct S3 : P {
> static func foo(_ v: T) -> (T, T, T) {
> return (v, v, v)
> }
> }
> 
> (I'm guessing but am not sure that I've run into (yet) a(nother) situation 
> which would require higher kinded types?)
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Is "lazy let" on the schedule anywhere?

2017-06-26 Thread Slava Pestov via swift-users
If you’re not passing the value type as an inout, how will the ‘lazy let’ 
property write back the new value?

Slava

> On Jun 26, 2017, at 3:32 PM, Edward Connell via swift-users 
>  wrote:
> 
> It sure would be nice if the compiler supported lazy lets for structs. Any 
> idea when or if this will be supported? 
> 
> Seems like a nice performance win, lazy var is a pain because you can't 
> access arguments passed into a function without mutation complaints.
> 
> Thanks, Ed
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Optional generics question

2017-06-08 Thread Slava Pestov via swift-users

> On Jun 8, 2017, at 11:11 AM, Joel Loeshelle via swift-users 
>  wrote:
> 
> Hi all,
> 
> Is there any support for having an optional type in an initializer? My use 
> case is I want to have a struct SectionWrapper that includes information 
> about a Collection View Section. So you can pass the CellType, Cell Data 
> Source, and an Optional HeaderType and HeaderDataSource if there is a Section 
> Header. Here's the code. I first have a protocol ViewModelConfigurable that 
> the Cell and Header subclasses conform to:
> 
> protocol ViewModelConfigurable
> {
> associatedtype ViewModelType
> 
> func configure(with viewModel : ViewModelType);
> }
> 
> class TestCell : UICollectionViewCell, ViewModelConfigurable
> {
> typealias ViewModelType = String
> func configure(with viewModel: String) {
> //todo
> }
> }
> 
> class HeaderFooter : UICollectionReusableView, ViewModelConfigurable
> {
> typealias ViewModelType = String
> func configure(with viewModel: String) {
> //todo
> }
> }
> 
> I then have a SectionWrapper struct where I want to initialize with a 
> concrete UICollectionViewCell type that conforms to ViewModelType and pass 
> the associated dataSource which must be an array of ViewModelType. I also 
> want to have the ability to pass an optional UICollectionReusableView type 
> that conforms to ViewModelType with the associated dataSource. You could then 
> pass nil if this section does not have a Header. See below:
> 
> struct SectionWrapper
> {
> let cellConfigure: (UICollectionViewCell, Int) -> ()
> let headerConfigure: ((UICollectionReusableView) -> ())?
> 
> init HeaderType : UICollectionReusableView & ViewModelConfigurable>(cellType : 
> ActualCellType.Type, cellDataSource : [ActualCellType.ViewModelType], 
> headerType : (HeaderType.Type)?, headerDataSource : 
> (HeaderType.ViewModelType)?)
> {
> self.cellConfigure = { cell, index in
> (cell as! ActualCellType).configure(with: cellDataSource[index])
> }
> 
> if let headerDataSource = headerDataSource
> {
> self.headerConfigure = { header in
> (header as! HeaderType).configure(with: headerDataSource);
> }
> }
> else
> {
> self.headerConfigure = nil
> }
> }
> }
> 
> If I pass nil for headerType and headerDataSource, I get the following error: 
> error: Swift4Test.playground:86:31: error: generic parameter 'ActualCellType' 
> could not be inferred
>  let noHeader = SectionWrapper.init(cellType: TestCell.self, cellDataSource: 
> ["Test"], headerType: nil, headerDataSource: nil) //Gives error
> 
> 
> let header = SectionWrapper.init(cellType: TestCell.self, cellDataSource: 
> ["Test"], headerType: HeaderFooter.self, headerDataSource: "Header") //No 
> error
> 
> let noHeader = SectionWrapper.init(cellType: TestCell.self, cellDataSource: 
> ["Test"], headerType: nil, headerDataSource: nil) //Gives error
> 
> 
> I have also attached the Playground that I'm working through. Please let me 
> know if you have any questions and thanks in advance for your help!

You could overload SectionWrapper.init(), providing two versions: one takes 
non-optional headerType and headerDataSource parameters, and the other does not 
take them at all, and only has a single generic parameter for ActualCellType.

Unfortunately we don’t support explicit specialization on function calls right 
now; if we did, you could write SectionWrapper.init to explicitly bind 
the generic arguments.

Slava


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

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


Re: [swift-users] Swift 4 protocol with associatedtype conforming to itself

2017-06-07 Thread Slava Pestov via swift-users

> On Jun 7, 2017, at 12:46 AM, Jens Persson  wrote:
> 
> Ok, I thought it was part of SE-0142 (which has status "implemented (Swift 
> 4)”.

That’s just the where clause part. There’s still plenty you can accomplish with 
them even if they do not introduce recursive conformances :)

Slava

> /Jens
> 
> On Wed, Jun 7, 2017 at 9:39 AM, Slava Pestov  > wrote:
> This is a rather complex feature that is not actually implemented in Swift 4 
> (or Swift 3 for that matter). Work is underway to support this, though. The 
> fact that the second example does not produce a diagnostic is a bug (probably 
> you will not be able to define a type that conforms to P2 anyway).
> 
> The proposal is here if you’d like to read more about it: 
> https://github.com/apple/swift-evolution/blob/master/proposals/0157-recursive-protocol-constraints.md
>  
> 
> 
> Slava
> 
> > On Jun 6, 2017, at 10:37 PM, Jens Persson via swift-users 
> > > wrote:
> >
> > In Swift 4:
> >
> > protocol P1 {
> > associatedtype A: P1 // Error: Type may not reference itself as a 
> > requirement
> > }
> > protocol P2 {
> > associatedtype A where A: P2 // OK
> > }
> >
> > What is the rationale behind this?
> >
> > /Jens
> > ___
> > swift-users mailing list
> > swift-users@swift.org 
> > https://lists.swift.org/mailman/listinfo/swift-users 
> > 
> 
> 

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


Re: [swift-users] Swift 4 protocol with associatedtype conforming to itself

2017-06-07 Thread Slava Pestov via swift-users
This is a rather complex feature that is not actually implemented in Swift 4 
(or Swift 3 for that matter). Work is underway to support this, though. The 
fact that the second example does not produce a diagnostic is a bug (probably 
you will not be able to define a type that conforms to P2 anyway).

The proposal is here if you’d like to read more about it: 
https://github.com/apple/swift-evolution/blob/master/proposals/0157-recursive-protocol-constraints.md

Slava

> On Jun 6, 2017, at 10:37 PM, Jens Persson via swift-users 
>  wrote:
> 
> In Swift 4:
> 
> protocol P1 {
> associatedtype A: P1 // Error: Type may not reference itself as a 
> requirement
> }
> protocol P2 {
> associatedtype A where A: P2 // OK
> }
> 
> What is the rationale behind this?
> 
> /Jens
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Associatedtype Naming Conventions

2017-05-31 Thread Slava Pestov via swift-users

> On May 31, 2017, at 4:16 PM, Steven Brunwasser  wrote:
> 
> Basically, my library contains a bunch of collection-like protocols, which 
> can be combined in different ways and can be compatible with each other in 
> certain combinations when the proper types align. Naturally, they all have an 
> Element associatedtype, but I need to allow for the possibility where two of 
> these collection protocols are implemented in the same structure that 
> requires different type definitions for each protocols' Element.

Oh, I understand now. This is intentionally not supported — associated types 
with the same name from different protocols must all be implemented by the same 
typealias in the conforming type.

Slava

> 
> I’ve been trying to make some other protocols to simplify some definitions, 
> but specifying a parent protocol’s associated type within a child protocol 
> doesn’t seem to work.
> 
>   protocol Buzz: Bar {
>   typealias Container = A
>   }
> 
>   struct BuzzImpl: Buzz {} // error: type ‘BuzzImpl' does not conform to 
> protocol ‘Buzz'
> 
> On May 31, 2017 at 4:02:43 PM, Slava Pestov (spes...@apple.com 
> ) wrote:
> 
>> Can you give an example of a problematic name collision? Does fully 
>> qualifying names not help?
>> 
>> Slava
>> 
>>> On May 31, 2017, at 4:01 PM, Steven Brunwasser via swift-users 
>>> > wrote:
>>> 
>>> Hi,
>>> 
>>> I have a library which uses a few generic protocols with identically named 
>>> associated types that may not always be specified identically by 
>>> implementors.
>>> 
>>> protocol Foo {
>>> associatedtype Container
>>> associatedtype Element
>>> }
>>> 
>>> protocol Bar {
>>> associatedtype Container
>>> associatedtype Element
>>> }
>>> 
>>> struct Baz: Foo, Bar {
>>> // Implement using two different Container/Element types.
>>> }
>>> 
>>> Is there a consensus on some naming convention for associatedtypes to 
>>> mitigate name collisions?
>>> Would it be acceptable to add namespace prefixes to these types?
>>> 
>>> protocol Foo {
>>> associatedtype FooContainer
>>> associatedtype FooElement
>>> }
>>> 
>>> I’m using the dictionary and thesaurus to find some alternative names I 
>>> could use, but the ones already used are so the most sensical semantically.
>>> 
>>> Do you have any suggestions?
>>> 
>>> Thanks, 
>>> - Steve Brunwasser
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Associatedtype Naming Conventions

2017-05-31 Thread Slava Pestov via swift-users
Can you give an example of a problematic name collision? Does fully qualifying 
names not help?

Slava

> On May 31, 2017, at 4:01 PM, Steven Brunwasser via swift-users 
>  wrote:
> 
> Hi,
> 
> I have a library which uses a few generic protocols with identically named 
> associated types that may not always be specified identically by implementors.
> 
>   protocol Foo {
>   associatedtype Container
>   associatedtype Element
>   }
> 
>   protocol Bar {
>   associatedtype Container
>   associatedtype Element
>   }
> 
>   struct Baz: Foo, Bar {
>   // Implement using two different Container/Element types.
>   }
> 
> Is there a consensus on some naming convention for associatedtypes to 
> mitigate name collisions?
> Would it be acceptable to add namespace prefixes to these types?
> 
>   protocol Foo {
>   associatedtype FooContainer
>   associatedtype FooElement
>   }
> 
> I’m using the dictionary and thesaurus to find some alternative names I could 
> use, but the ones already used are so the most sensical semantically.
> 
> Do you have any suggestions?
> 
> Thanks, 
> - Steve Brunwasser
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] override-like keyword for default implementations

2017-05-16 Thread Slava Pestov via swift-users
It’s not clear if such a keyword can be designed in a way that covers all 
cases. For example, consider a protocol extension that provides a default 
implementation for a requirement in a different protocol:

protocol R {
  func f()
}

protocol P {}

extension P {
  func f()
}

struct S : R, P {}

Or a constrained extension that provides a default that only applies in certain 
cases:

protocol P {
  func f()
}

extension P where Self : AnyObject {
  func f()
}

class C : P {}

Slava

> On May 16, 2017, at 8:53 AM, Johannes Weiss via swift-users 
>  wrote:
> 
> Hi swift-users,
> 
> Is there anything like the `override` keyword for making sure that default 
> implementations in protocols are not adding a new function?
> 
> An example would be the following:
> 
>protocol FooProto {
>func foo()
>}
> 
>extension FooProto {
>func foo() { /* <-- can I mark this as being a default implementation 
> */
>print("foo default")
>}
>}
> 
> Right now, there's a `func foo()` default implementation for `FooProto` but 
> if later of `foo` gets refactored to `bar`, we lose the default 
> implementation which can lead to problems.
> 
> Is there anything in Swift (like the `override` keyword) that allows me to 
> say this is a default implementation and not a new method?
> 
> Thanks,
>  Johannes
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Swift build-script Smaller Memory Footprint?

2017-05-07 Thread Slava Pestov via swift-users
On Darwin (which uses its own linker and not GNU ld), you can definitely build 
Swift with less than 16GB of RAM available.

Maybe you could try gold?

Slava

> On May 6, 2017, at 7:21 PM, Brandon B via swift-users  
> wrote:
> 
> Hello,
> 
> I’m installing Swift 3 on FreeBSD 11. After installing the necessary 
> dependencies, I now only need to run the build-script.
> 
> The problem is that I cannot proceed beyond:
> 
> >  Linking CXX executable bin/llvm-lto
> 
> because I consistently run out of memory on my 16GB server.
> 
> From what I’ve gathered, the problem lies in  ld  which is apparently 
> infamous for this sort of behavior.
> 
> I know that I can run ld without debug options (which would reduce its memory 
> footprint dramatically) but I don’t know how I would do that, given that it 
> is called by the build-script.
> 
> What do I need to do to make the build-script use less memory?
> 
> — Brandon Bradley
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] How to use a protocol to infer a generic type with constraints

2017-05-02 Thread Slava Pestov via swift-users
Hi Satoshi,

Protocols do not conform to themselves. Only concrete types can conform to 
protocols in the current implementation of Swift.

Slava

> On May 2, 2017, at 1:57 AM, Satoshi Nakagawa via swift-users 
>  wrote:
> 
> Hi,
> 
> I got a build error "Generic parameter 'T' could not be inferred" for the 
> following code.
> 
> Can anyone explain why we can't use a protocol to infer the generic type T?
> 
> class Emitter {
> func emit() -> T {
> ...
> }
> }
> 
> protocol Emittable {}
> protocol Subemittable: Emitable {}
> 
> class ConcreteEmittable: Subemittable {}
> 
> func testCode() {
> let emitter = Emitter()
> 
> // Error: Generic parameter 'T' could not be inferred
> let _: Emittable = emitter.emit()
> 
> // Error: Generic parameter 'T' could not be inferred
> let _: Subemittable = emitter.emit()
> 
> // This works
> let _: ConcreteEmittable = emitter.emit()
> }
> 
> Thanks,
> Satoshi
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Performance in Trunk builds vs 3.1.1

2017-04-25 Thread Slava Pestov via swift-users
Can you share the code for your benchmark?

Slava

> On Apr 25, 2017, at 6:34 AM, Proyb P via swift-users  
> wrote:
> 
> I have testing the performance between trunk builds downloaded from Swift 
> website (April 22 and 24) and 3.1.1
> 
> Fibonacci (N: 50) benchmark:
> Trunk (22 Apr): 1m13s
> Trunk (24 Apr): 1m16s
> 3.1.1: 1m7s
> 
> I assume there are overhead in trunk build? There is a big regression.
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Swift creduce

2017-04-19 Thread Slava Pestov via swift-users
Huon noticed that creduce actually works pretty well with Swift as-is. I’ve 
been using it without any issues.

Slava

> On Apr 19, 2017, at 3:53 PM, Doug Hill via swift-users 
>  wrote:
> 
> Is there a version of 'creduce' for Swift?
> 
> I did some basic googling and didn't find anything, so I thought I'd ask here.
> 
> Thanks.
> 
> Doug Hill
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Compile time tests

2017-03-31 Thread Slava Pestov via swift-users
We have an undocumented -verify flag you can use for this. Here’s some code 
that doesn’t type check because the second call to g() is passing a type that 
does not conform to protocol P:

protocol P {}
protocol Q {}

struct R : P {}
struct S : Q {}

func g(_: T) {}

g(R())
g(S()) // expected-error{{does not conform}}

——

When you run this file through swiftc and pass the magic incarnation 
‘-typecheck -Xfrontend -verify’, the compiler exits with a code of 0 indicating 
success, because a diagnostic was produced on the line with the 
‘expected-error’ directive, and no other errors were produced:

Slavas-MBP:swift slava$ 
../build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin/swiftc -typecheck 
-Xfrontend -verify generics.swift
Slavas-MBP:swift slava$ echo $?
0

You’ll need to come up with some way to wire the above up into your test 
harness, because as you correctly observed we never allow ill-typed code to 
*execute*.

It goes without saying that anything involving -Xfrontend is 
undocumented/unsupported/can change at any time. And of course the phrasing of 
the diagnostics can and will change too, which would also cause your test to 
fail. But we use this functionality extensively in our own test suite — it’s 
how we ensure that diagnostics don’t regress and invalid code is rejected in a 
clean way instead of crashing.

Slava

> On Mar 31, 2017, at 12:44 AM, José Manuel Sánchez via swift-users 
>  wrote:
> 
> I don’t know if this has come before (I tried searching but it’s not easy 
> with the mailing lists system); sorry in advance if that’s the case.
> 
> I’ve been using more generics lately, and I’ve come to a point where it would 
> be really nice to check if my types are correctly specified so that a wrong 
> combination isn’t possible because the compiler will not allow it. The 
> problem is, I can’t do this using unit testing, because if everything is 
> correct, the code won’t compile, and then the tests will fail. I’m guessing 
> there’s currently no way to do this? I did some googling and I only found 
> something like this for boost (compile-fail):
> 
> http://www.boost.org/build/doc/html/bbv2/builtins/testing.html 
> 
> 
> Regards
> José Manuel
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Protocol conformance failure

2017-03-21 Thread Slava Pestov via swift-users
Worth mentioning that @objc protocols do conform to themselves as long as they 
do not have static methods or initializer requirements. However this may be too 
heavy-handed if a simple overload can do the trick.

Slava

> On Mar 9, 2017, at 1:10 PM, Guillaume Lessard via swift-users 
>  wrote:
> 
> 
>> On Mar 9, 2017, at 12:46, Edward Connell via swift-users 
>>  wrote:
>> 
>> // Everything compiles fine until this
>> someFunc(items: items)
> 
> This is a frequent pain point: protocol existentials cannot stand in for the 
> protocol they represent.
> Your function wants a concrete type that conforms to ItemProtocol, but an 
> array of disparate types which happen to separately conform to ItemProtocol 
> does not do that.
> 
> You will need to overload thusly:
> 
> func someFunc(items: [ItemProtocol]) {
>  for item in items {
>print(item.message)
>  }
> }
> 
> until, someday, this pain point is resolved.
> 
> Cheers,
> Guillaume Lessard
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] inline best practices?

2017-03-02 Thread Slava Pestov via swift-users
Here’s an overview of @inline(__always):

- It is an annotation for the performance inliner, which only runs in -O 
builds. The performance inliner uses heuristics to figure out what to inline, 
so most of the time explicit annotations are not necessary, and sometimes it 
won’t inline something even if its @inline(__always) — for example, inlining of 
generics is not enabled in 3.1 yet, because of code size concerns. We might 
change this behavior to make @inline(__always) mandatory one day.

- Public inline always functions have the additional behavior that they can be 
inlined into other modules, with caveats.

- In Swift 3.0, if a public inline always function references private symbols 
and is referenced from another module, you’ll get linker errors or a compiler 
crashes. In 3.1, we added diagnostics for this as part of the resilience model, 
but it’s totally a work in progress.

- The compiled body (more precisely, the SIL IR) for public inline always 
functions are serialized into the .swiftmodule file when a module is built with 
WMO.

- When building a library with WMO off, serialized SIL is simply discarded, 
which is a bug we intend on fixing.

- The @_transparent attribute is another low-level attribute that was never 
officially supported but some people have used it anyway. Transparent functions 
are inlined during mandatory optimizations, so you get it even in -Onone, 
subject to the same limitations on SIL serialization, what they can reference, 
etc. Transparent has other quirks around debug info and other things too. 
There’s a chance @_transparent will go away entirely. Please do not use it.

- There’s an @_inlineable attribute in master that’s a weaker form if 
@inline(__always). It enables the same restrictions on symbol references as 
@inline(__always), without changing the behavior of the performance inliner. 
This is needed because most of the time it’s not inlining you care about with 
generics, but being able to specialize the function body.

- The work on the library evolution model and ABI is centered on filling in the 
gaps in these attributes, documenting their behavior precisely and getting it 
all through swift-evolution — but there’s still a lot of heavy lifting left 
before we’re ready for that.

So the best practice is basically what Jordan said. Don’t use 
@inline(__always), @_inlineable, or @_transparent. But if you’re interested in 
helping with the design and implementation of these attributes, let us know.

Slava

> On Mar 2, 2017, at 4:27 PM, Erica Sadun via swift-users 
>  wrote:
> 
> Any best practices for `@inline(__always)`? When it's short? When has very 
> few call sites? When the abstraction aids reading but hinders computation?
> 
> Thanks -- E
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] question on generics

2017-02-22 Thread Slava Pestov via swift-users

> On Feb 22, 2017, at 4:23 PM, David Sweeris via swift-users 
>  wrote:
> 
> 
>> On Feb 22, 2017, at 16:08, Dave Reed via swift-users  
>> wrote:
>> 
>> I suspect this can't be done (at least not right now), but wanted to check.
>> 
>> I'd like to declare a class as a generic that meets a protocol and is also a 
>> subclass of some specific type.
>> 
>> Something like class Foo (i.e., the T must 
>> be both a NSManagedObject or subclass of it and conform to SomeProtocol).
>> 
>> Is this possible?
> 
> Yep
> class Foo  where T:  SomeProtocol {...}
> should work fine (although I'm not in front of my computer to double check)

Also this might be more readable,

class Foo where T : NSManagedObject, T : SomeProtocol { … }

Slava

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

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


Re: [swift-users] question about covariant subtyping

2017-02-22 Thread Slava Pestov via swift-users
It looks intentional.

Function conversions can be performed on argument and return types that are 
related via ‘Subtype’ constraints in the constraint solver, however array 
conversions are only possible via the ‘Conversion’ relation.

Changing this would require some additional work in SILGen to support such 
function conversions.

Slava

> On Feb 22, 2017, at 3:06 PM, Joe Groff via swift-users 
>  wrote:
> 
>> 
>> On Feb 22, 2017, at 8:50 AM, Michael Roitzsch via swift-users 
>>  wrote:
>> 
>> Hi all,
>> 
>> I am fairly new to Swift, so this may very well be a simple misunderstanding 
>> on my part.
>> 
>> I was exploring the subtyping rules of Swift, especially regarding 
>> covariance. I came across two examples where the outcome puzzles me and I 
>> would appreciate if someone could explain this to me.
>> 
>> First I tried the covariance for the standard container types. Here is an 
>> excerpt from a REPL session:
>> 
>> Michael@carpo:~ > swift
>> Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). 
>> Type :help for assistance.
>> 1> open class Super {}; class Sub: Super {}
>> 2> print([Sub()] is [Sub])
>> true
>> 3> print([Sub()] is [Super])
>> true
>> 4> print(Array(arrayLiteral: Sub()) is [Sub])
>> true
>> 5> print(Array(arrayLiteral: Sub()) is [Super])
>> error: repl.swift:5:39: error: 'Super' is not a subtype of 'Sub'
>> print(Array(arrayLiteral: Sub()) is [Super])
>> ^~
>> 
>> Why does it matter for subtyping against [Super] whether I express an array 
>> as [Sub] or Array(arrayLiteral: Sub())?
>> 
>> Then I tried combining array covariance with function argument type 
>> contravariance:
>> 
>> Michael@carpo:~ > swift
>> Welcome to Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1). 
>> Type :help for assistance.
>> 1> open class Super {}; class Sub: Super {}
>> 2> func f(_: [Super]) {}
>> 3> let test: ([Sub]) -> Void = f
>> error: repl.swift:3:29: error: cannot convert value of type '([Super]) -> 
>> ()' to specified type '([Sub]) -> Void'
>> let test: ([Sub]) -> Void = f
>>   ^
>> 
>> Why is this assignment not possible? It works fine (as expected) when using 
>> plain Super and Sub instead of arrays.
> 
> Those are both bugs. There's no fundamental reason these should be errors.
> 
> -Joe
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Weird function call behaviour

2017-02-22 Thread Slava Pestov via swift-users

> On Feb 22, 2017, at 1:01 PM, David Hart <david.w.h...@me.com> wrote:
> 
> 
>> On 22 Feb 2017, at 21:59, Slava Pestov via swift-users 
>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>> 
>> When a class conforms to a protocol and a requirement is fulfilled by a 
>> method in an extension, the class does not get a vtable entry for the 
>> extension method. So it cannot be overridden in a subclass — there’s nothing 
>> to dynamically dispatch here. We plan on addressing this as part of ABI 
>> stability.
> 
> What do you mean by “address” this? Force the vtable entry?

Yeah. Instead of having the witness table for the conformance point directly to 
the extension method, if the conforming type is a class, we will generate a 
small thunk that calls a vtable entry, and store the extension method in that 
vtable entry.

Of course this will only work if the conformance is defined in the same 
translation unit as the class; if you define the extension in a different 
module, you’ll get the same behavior you observe below.

Slava

> 
>> Slava
>> 
>> 
>>> On Feb 22, 2017, at 9:39 AM, David Hart via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> In the following piece of code, can somebody explain the last result? Why 
>>> the break in consistency? Is this a bug?
>>> 
>>> protocol P {
>>> func foo() -> String
>>> }
>>> 
>>> extension P {
>>> func foo() -> String { return "P" }
>>> }
>>> 
>>> class A : P {
>>> func foo() -> String { return "A" }
>>> }
>>> 
>>> class B : P {}
>>> class C : B {
>>> func foo() -> String { return "C" }
>>> }
>>> 
>>> A().foo()  // A
>>> (A() as P).foo()   // A
>>> B().foo()  // P
>>> (B() as P).foo()   // P
>>> C().foo()  // C
>>> (C() as P).foo()   // P
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto:swift-users@swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

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


Re: [swift-users] The case of broken polymorphism or "Cannot convert value of type to expected argument type"?

2017-02-21 Thread Slava Pestov via swift-users

> On Feb 20, 2017, at 4:17 PM, Jon Shier  wrote:
> 
> Also possibly related is the covariance in protocol requirements. The 
> following example doesn’t compile without casting the arrays or single values 
> to the exact types required in the protocols, despite being covariant through 
> protocol conformance or subclass.
> 
> protocol HasViews {
> 
> var views: [UIView]!
> 
> }
> 
> protocol Updateable { }
> 
> extension UIView: Updateable { }
> 
> protocol HasProtocols {
> 
> var updateables: [Updateable]!
> 
> }
> 
> class ViewController: UIViewController {
> 
> @IBOutlet var views: [UIButton]!
> @IBOutlet var updateables: [UIButton]!
> 
> }
> 
> extension ViewController: HasViews { } // fails without casting
> extension ViewController: HasProtocols { } // fails without casting

This kind of thing we do want to support eventually, I think.

Method overrides support a limited form of variance — you can make method 
parameters more optional in an override, or change their type to a base class; 
similarly a method return type can becomes less optional or change to a 
subclass. Overrides do not support converting to a protocol existential though.

Protocol requirements do not support variance at all, except for @objc 
protocols, which allow the same optionality changes as method overrides (but no 
class upcasts!)

This is all quite confusing to remember, and it would be great to see a 
proposal that makes the rules more general and consistent between method 
overrides in classes and protocol requirement witnesses.

Slava

> 
> 
> 
> Jon
> 
> 
>> On Feb 20, 2017, at 7:07 PM, Howard Lovatt via swift-users 
>> > wrote:
>> 
>> It is confusing in Swift what can be covariant and what is invariant, 
>> consider:
>> 
>> // Covarant arrays work
>> class A {}
>> class B: A {}
>> let a = A() // A
>> let b = B() // B
>> var arrayA = [a] // Array
>> arrayA[0] = b // OK
>> 
>> // And arrays of arrays
>> var arrayArrayA = [arrayA] // Array
>> arrayArrayA[0][0] = b // OK
>> let arrayB = [b] // Array
>> arrayArrayA[0] = arrayB // OK, works out that an Array is a Array
>> 
>> // Covariant homebrew-collections work
>> class C { 
>> var e: T
>> init(_ e: T) { self.e = e }
>> }
>> var cA = C(a) // C
>> cA.e = b // OK
>> 
>> // But not quite for homebrew-collections of homebrew-collections
>> var cCA = C(cA) // C
>> cCA.e.e = b // OK
>> let cB = C(b) // C
>> // cCA.e = cB // Error - cannot work out that a C is a C but can 
>> do so for arrays
>> 
>> It is weird that the last line fails and the equivalent Array line doesn't. 
>> I suspect that there is some special typing going on for arrays, probably to 
>> make them play nice with Objective-C. However it would be simpler if 
>> everything was covariant when safe to be covariant, i.e. The last line 
>> should work.
>> 
>>  -- Howard.
>> 
>> On Mon, 20 Feb 2017 at 8:38 pm, Isaac Rivera via swift-users 
>> > wrote:
>> I can see it is a (counter-intuitive) language design decision for type 
>> safety… but then why, in the code below I can:
>> 
>> class OtherThing: Something {
>>  override func start(_ completion: SomeCallback? = nil) {
>>  // implementation details...
>>  }
>> }
>> 
>> let firstThing = OtherThing(viewController: UINavigationController())
>> 
>> OtherThing extends Something… but I can instantiate it 
>> with the subtype…
>> 
>> Ok you will say, UINavigationController is a subtype of UIViewController, 
>> but that still does not make Something a subtype of 
>> Something. 
>> 
>> Fair enough, but:
>> 
>> let c1: Something = Something(viewController: 
>> UINavigationController())
>> // c1 is of type "Something"
>> 
>> let c2 = Something(viewController: UINavigationController())
>> // c1 is of type "Something”
>> 
>> So it appears Something can be cast to type 
>> Something…
>> 
>> Yet this is illegal?
>> 
>> let somethings: [Something] = [c1, c2]
>> 
>> I dont know, something seems inconsistent.
>> 
>> 
>>> On Feb 16, 2017, at 10:59 PM, Slava Pestov >> > wrote:
>>> 
>>> Hi Isaac,
>>> 
>>> This is not about associated types. Rather, the issue is that a ‘Thing’ is 
>>> a ‘Something’, but you are casting it to 
>>> ‘Something’. The two types are not related; in general, 
>>> if A is a subtype of B, then G is not a subtype of G.
>>> 
>>> https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)
>>>  
>>> 
>>> 
>>> Slava
>>> 
 On Feb 16, 2017, at 9:05 AM, Isaac Rivera via swift-users 
 > wrote:
 
 Hello, list!
 
 I am trying to find my way around 

Re: [swift-users] The case of broken polymorphism or "Cannot convert value of type to expected argument type"?

2017-02-21 Thread Slava Pestov via swift-users

> On Feb 20, 2017, at 4:07 PM, Howard Lovatt  wrote:
> 
> It is confusing in Swift what can be covariant and what is invariant, 
> consider:
> 
> // Covarant arrays work
> class A {}
> class B: A {}
> let a = A() // A
> let b = B() // B
> var arrayA = [a] // Array
> arrayA[0] = b // OK
> 
> // And arrays of arrays
> var arrayArrayA = [arrayA] // Array
> arrayArrayA[0][0] = b // OK
> let arrayB = [b] // Array
> arrayArrayA[0] = arrayB // OK, works out that an Array is a Array

There are implicit conversions from Array to Array if T < U, and 
similarly for Optional, so they’re covariant in this sense (but it’s an 
explicit runtime conversion behind the scenes).

> 
> // Covariant homebrew-collections work
> class C { 
> var e: T
> init(_ e: T) { self.e = e }
> }
> var cA = C(a) // C
> cA.e = b // OK

This is actually not covariance, you’re just upcasting ‘b’ to ‘a’ before 
calling the setter for cA.e. ‘cA’ is still a C, not a C.

> 
> // But not quite for homebrew-collections of homebrew-collections
> var cCA = C(cA) // C
> cCA.e.e = b // OK
> let cB = C(b) // C
> // cCA.e = cB // Error - cannot work out that a C is a C but can do 
> so for arrays
> 
> It is weird that the last line fails and the equivalent Array line doesn't. I 
> suspect that there is some special typing going on for arrays, probably to 
> make them play nice with Objective-C. However it would be simpler if 
> everything was covariant when safe to be covariant, i.e. The last line should 
> work.

The problem is determining if something is safe. For example,

class Base {}
class Derived : Base {}

struct Covariant {
  func returns() -> T { … }
}

Here, you would want Covariant to be a subtype of Covariant, 
because Covariant.returns produces a Derived, which is certainly a 
subtype of Base.

This is contravariant though:

struct Contravariant {
  func takes(_: T)
}

Contravariant is now a subtype of Contravariant, not the other 
way around (proof is an exercise for the reader).

Ok, so that’s all very well and good, and we could in fact infer this from 
looking at the types of the members. However, if the library author adds new 
members, or you add new members in an extension, a generic parameter that was 
previously covariant or contravariant could now become invariant, breaking 
source compatibility and ABI.

Also, there is the issue of representation changes. If a concrete type C 
conforms to a protocol P, then we model C as a subtype of P, but at runtime a 
conversion is required and the two types have values with different size, etc. 
I’m not sure how we would model this in general.

So I’d rather draw a line in the sand and say that Swift generics should never 
support variance, except for the simple cases of arrays and optionals which are 
baked into the type checker.

Slava

> 
>  -- Howard.
> 
> On Mon, 20 Feb 2017 at 8:38 pm, Isaac Rivera via swift-users 
> > wrote:
> I can see it is a (counter-intuitive) language design decision for type 
> safety… but then why, in the code below I can:
> 
> class OtherThing: Something {
>   override func start(_ completion: SomeCallback? = nil) {
>   // implementation details...
>   }
> }
> 
> let firstThing = OtherThing(viewController: UINavigationController())
> 
> OtherThing extends Something… but I can instantiate it with 
> the subtype…
> 
> Ok you will say, UINavigationController is a subtype of UIViewController, but 
> that still does not make Something a subtype of 
> Something. 
> 
> Fair enough, but:
> 
> let c1: Something = Something(viewController: 
> UINavigationController())
> // c1 is of type "Something"
> 
> let c2 = Something(viewController: UINavigationController())
> // c1 is of type "Something”
> 
> So it appears Something can be cast to type 
> Something…
> 
> Yet this is illegal?
> 
> let somethings: [Something] = [c1, c2]
> 
> I dont know, something seems inconsistent.
> 
> 
>> On Feb 16, 2017, at 10:59 PM, Slava Pestov > > wrote:
>> 
>> Hi Isaac,
>> 
>> This is not about associated types. Rather, the issue is that a ‘Thing’ is a 
>> ‘Something’, but you are casting it to 
>> ‘Something’. The two types are not related; in general, if 
>> A is a subtype of B, then G is not a subtype of G.
>> 
>> https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)
>>  
>> 
>> 
>> Slava
>> 
>>> On Feb 16, 2017, at 9:05 AM, Isaac Rivera via swift-users 
>>> > wrote:
>>> 
>>> Hello, list!
>>> 
>>> I am trying to find my way around Swift’s protocol limitations. It appears 
>>> that in general, any protocol with declared associatedtype will break 
>>> polymorphism?
>>> 

Re: [swift-users] The case of broken polymorphism or "Cannot convert value of type to expected argument type"?

2017-02-16 Thread Slava Pestov via swift-users
Hi Isaac,

This is not about associated types. Rather, the issue is that a ‘Thing’ is a 
‘Something’, but you are casting it to 
‘Something’. The two types are not related; in general, if A 
is a subtype of B, then G is not a subtype of G.

https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

Slava

> On Feb 16, 2017, at 9:05 AM, Isaac Rivera via swift-users 
>  wrote:
> 
> Hello, list!
> 
> I am trying to find my way around Swift’s protocol limitations. It appears 
> that in general, any protocol with declared associatedtype will break 
> polymorphism?
> 
> Take the case below which does not compile. All "Thing” instances are 
> "Something” but they can’t be passed around or coerced 
> as so.
> 
> How is it that I can legally write the code:
> 
> class Thing: Something { }
> 
> and instantiate it, but it is not the very thing it implements? 
> 
> All Thing instances conform to the public interfaces of 
> Something so why can’t they be recognized as such and 
> coerced as such?
> 
> What is the work-around of this break in Polymorphism?
> 
> import UIKit
> 
> protocol Anything: class, NSObjectProtocol {
>   
>   associatedtype ViewControllerType: UIViewController
>   
>   var viewController: ViewControllerType { get }
>   
>   init(viewController: ViewControllerType)
>   
>   func addAnything(anything: Something) -> Bool
> }
> 
> class Something: NSObject, Anything {
>   
>   typealias ViewControllerType = VC
>   
>   private(set) var viewController: ViewControllerType
>   
>   required init(viewController: ViewControllerType) { self.viewController 
> = viewController }
>   
>   final private var things = [String: Something]()
>   
>   final internal func addAnything(anything: Something) 
> -> Bool {
>   // implementation details...
>   return true
>   }
> }
> 
> class Thing: Something { }
> 
> let firstThing = Thing(viewController: UINavigationController())
> let secondThing = Thing(viewController: UINavigationController())
> 
> firstThing.addAnything(anything: secondThing)
> 
> // Playground execution failed: error: MyPlayground.playground:48:34: error: 
> cannot convert value of type 'Thing' to expected argument type 
> 'Something'
> 
> firstThing.addAnything(anything: secondThing as Something)
> 
> // Playground execution failed: error: MyPlayground.playground:48:34: error: 
> cannot convert value of type 'Thing' to type 'Something' in 
> coercion
> 
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Getting started with development

2017-02-13 Thread Slava Pestov via swift-users
Here is the general guide for contributions:

https://swift.org/contributing/ 

If you want ideas for simple things to fix, look at the ‘StarterBug’ label in 
the bug tracker:

https://bugs.swift.org/issues/?jql=status%20in%20(Open%2C%20Reopened)%20AND%20labels%20%3D%20StarterBug

Good luck!

Slava

> On Feb 13, 2017, at 7:09 PM, Mohit Athwani via swift-users 
>  wrote:
> 
> Hello,
> I'm a master's student in computer science and as part of my degree, I have 
> to contribute to some well known open source repositories. I have been an iOS 
> developer since 5 years now and I'm wondering if anybody in the community can 
> help me get started with where to look for issues/bugs and how to go about 
> fixing them and sending pull requests.
> 
> Appreciate help in any form!
> 
> Thanks,
> 
> Mohit
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] How flatMap's signature is able to translate from Optional to [Type]?

2017-02-13 Thread Slava Pestov via swift-users

> On Feb 13, 2017, at 4:40 PM, Maxim Veksler via swift-users 
>  wrote:
> 
> I'm trying to understand the signature of flapMap that allows it to "strip 
> down" Optional from a type, when called on an Optional collection but remain 
> same type when called on a non option collection.
> 
> How would flatMap be implemented if would have been stand alone?
> 
> This for ex. I can't get to compile:
> 
> func flatMap(on: T, _ transform: 
> (Element) throws -> ElementOfResult?
> ) rethrows -> [ElementOfResult] {
> var result: [ElementOfResult] = []
> for element in on {
> if let newElement = try transform(element) {
> result.append(newElement)
> }
> }
> return result
> }

This doesn’t compile because there’s no relation between T.Element.Iterator and 
Element. I think you want to remove the Element type parameter altogether, and 
make the input type of flatMap into T.Element.Iterator.

Slava

> 
> 
> Additionally please see 2 related SO questions, for background.
> 
> http://stackoverflow.com/q/42213656 
> http://stackoverflow.com/q/42214880 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Collection Oddities

2017-02-07 Thread Slava Pestov via swift-users

> On Feb 7, 2017, at 8:14 PM, Guillaume Lessard via swift-users 
>  wrote:
> 
> I keep running into weird things with Swift 3 Collections.
> 
> A) Collection has its count property defined as an Int via IndexDistance:
> 
> public protocol Collection : Indexable, Sequence {
>associatedtype IndexDistance : SignedInteger = Int  // line 182 in 
> Collection.swift
>public var count: IndexDistance { get } // line 776
> }

This declaration specifies that the *default* associated type is Int, not that 
it’s *always* Int. A Collection implementation is free to use a different type 
as its IndexDistance if it wants.

> Given this, why can’t `count` be treated as an Int?
> 
> func intCount(of c: C) -> Int {
>  return c.count // nope!
> }
> 
> A numericCast is required here in order to “convert” what is 
> known-to-be-an-Int to an actual Int.
> Why this is so? IndexDistance is defined such that it must be an integer (“A 
> type that represents the number of steps between a pair of indices”)...
> What is gained by making it so generic that it can’t simply be an Int?
> 
> 
> B) Collection.Indices is a Collection of Index, *but*
> - Collection.Indices.Index is not the same type as Collection.IndexDistance

There’s no reason for them to be the same type for a generic Collection, just 
because they both happen to be Int for Array, though.

> - Collection.Indices.Iterator.Element is somehow not the automatically the 
> same type as Collection.Index
> (ugh)

I think you’re right that this is a generics limitation - we’re waiting on 
‘where clauses for associated types’ to make these two types equivalent.
 
> 
> The second seems like a conditional conformance issue, but the first one is 
> baffling.
> 
> I did find that with String.CharacterView:
> String.CharacterView.Indices.Index != String.CharacterView.IndexDistance
> although, as expected,
> String.CharacterView.Indices.IndexDistance == 
> String.CharacterView.IndexDistance
> (which provides an clear workaround.)
> 
> 
> ***
> I wanted to extend Collection with concurrentPerform; which seems simple on 
> the surface:
> 
> extension Collection {
>  public func concurrentPerform(task: @escaping (Self.Iterator.Element) -> 
> Void) {
>DispatchQueue.concurrentPerform(iterations: count) {
>  iteration in
>  task(self[indices[iteration]])
>}
>  }
> }
> … but that won’t do.
> 
> The closest thing I found that does work is this:
> 
> extension Collection {
>  public func concurrentPerform(task: @escaping (Self.Iterator.Element) -> 
> Void) {
>let count: Int = numericCast(self.count)
>let indexList = (0.. numericCast($0)) }
> 
>DispatchQueue.concurrentPerform(iterations: count) {
>  iteration in
>  task(self[indexList[iteration]])
>}
>  }
> }
> 
> Note the unfortunate creation of an array of Index.
> Generic Collection code is exhausting!

Maybe in this case it makes more sense to define this on RandomAccessCollection 
or even just Array instead?

Slava

> 
> Cheers,
> Guillaume Lessard
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Static type when expecting dynamic type

2017-02-02 Thread Slava Pestov via swift-users
The problem is were not marking the materializeForSet accessor in 
DefaultMutableReference.value as an override. Definitely a bug:

sil_vtable DefaultMutableReference {
  #MutableReference.init!initializer.1: 
_TFC1d23DefaultMutableReferencecfT_GS0_x_   // 
DefaultMutableReference.init() -> DefaultMutableReference
  #MutableReference.value!getter.1: _TFC1d23DefaultMutableReferenceg5valuex 
// DefaultMutableReference.value.getter
  #MutableReference.value!setter.1: _TFC1d23DefaultMutableReferences5valuex 
// DefaultMutableReference.value.setter
  #MutableReference.value!materializeForSet.1: _TFC1d16MutableReferencem5valuex 
// MutableReference.value.materializeForSet
  #DefaultMutableReference.value!materializeForSet.1: 
_TFC1d23DefaultMutableReferencem5valuex   // 
DefaultMutableReference.value.materializeForSet

The last entry should not exist.

I’ll have a fix shortly.

Slava

> On Feb 2, 2017, at 9:04 AM, Jordan Rose via swift-users 
>  wrote:
> 
> Seems like a bug, and moreover it seems like a regression from Swift 3.0. 
> Mind filing a report at bugs.swift.org ?
> 
> Thanks!
> Jordan
> 
>> On Feb 1, 2017, at 20:49, Howard Lovatt via swift-users 
>> > wrote:
>> 
>> Hi All,
>> 
>> Anyone know what is going on here:
>> 
>> //: Closure picks up static type not dynamic
>> 
>> class MutableReference {
>> init() {
>> guard type(of: self) != MutableReference.self else {
>> fatalError("MutableReference is an abstract class; create a 
>> derrivative of MutableReference")
>> }
>> }
>> var value: T {
>> get {
>> fatalError("Calculated property value getter should be 
>> overridden")
>> }
>> set {
>> fatalError("Calculated property value setter should be 
>> overridden")
>> }
>> }
>> }
>> 
>> class DefaultMutableReference: MutableReference {
>> private var _value: T
>> override var value: T {
>> get {
>> return _value
>> }
>> set {
>> _value = newValue
>> }
>> }
>> init(_ value: T) {
>> _value = value
>> }
>> }
>> 
>> let e: (MutableReference<[Int]>, Int) -> Void = { $0.value.append($1) }
>> let dmr = DefaultMutableReference([2])
>> dmr.value // [2]
>> e(dmr, 2) // fatal error: Calculated property value getter should be 
>> overridden
>> dmr.value // Expect [2, 2]  
>> If I change `e` to:
>> 
>> let e: (DefaultMutableReference<[Int]>, Int) -> Void = { 
>> $0.value.append($1) }
>> It works fine.
>> 
>> IE the closure is using the static type of its first argument and not 
>> dynamically dispatching.
>> 
>> Am I doing something wrong? Is there a way round where I can still use the 
>> base class for `e`?
>> 
>> 
>> 
>> Thanks for any help in advance,
>> 
>> -- Howard.
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-users
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Initializers

2017-01-27 Thread Slava Pestov via swift-users

> On Jan 27, 2017, at 10:39 AM, tuuranton--- via swift-users 
>  wrote:
> 
> Yes, but why?
> 
> What's the rationale for this?
> 
> What would be so bad about allowing overriding a non-failable initializer 
> with a failable initializer?

If the non-failable initializer witnesses a non-failable protocol requirement, 
and the subclass overrides it, what should be the runtime behavior if the 
subclass initializer returns nil? The caller won’t expect it, since the caller 
is calling a non-failable initializer.

For similar reasons, you cannot override a method that returns a non-optional 
value with a method returning an optional value.

Slava

> 
> 27. Jan 2017 18:59 by saa...@saagarjha.com :
> 
> You can’t override a designated initializer with one that is failable. The 
> second one is defining a new initializer that is failable, instead of 
> overriding the one from its superclass.
> 
> Saagar Jha
> 
> On Jan 27, 2017, at 8:45 AM, tuuranton--- via swift-users 
> > wrote:
> 
> See the comments. Why is one allowed but the other one isn't and what's the 
> rationale for this?
> 
> 
> class Vehicle {
> let name: String
> init(name: String) {
> self.name = name
> }
> }
> 
> 
> class Car: Vehicle {
> //Why is this not allowed?
> override init?(name: String) {
> super.init(name: name)
> }
> 
> //But this is allowed?
> init?(name: String, ignore: String) {
> super.init(name: name)
> }
> }
> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org 
> https://lists.swift.org/mailman/listinfo/swift-users 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Protocol extension gotcha... or bug?

2017-01-23 Thread Slava Pestov via swift-users

> On Jan 23, 2017, at 7:31 AM, Wagner Truppel via swift-users 
>  wrote:
> 
> Say you have a protocol and an extension of it, like so:
> 
> protocol P {
>   var item: String { get }
> }
> 
> extension P {
>   var item: String {
>   return "P"
>   }
> }
> 
> Now imagine a class that conforms to that protocol and uses the property 
> declared there but doesn’t specialise it in any way:
> 
> class A: P {
>   var usedItem: String {
>   return item // A uses 'item' but doesn't override or specialise it in 
> any way
>   }
> }
> 
> let a = A()
> a.item // returns “P"
> a.usedItem // returns “P"
> 
> Not surprisingly, both results equal “P” since A doesn’t specialise 'item'. 
> Now imagine a class B that subclasses A and *does* specialise 'item':
> 
> class B: A {
>   var item: String { // subclass specialises 'item' by "overriding" the 
> protocol extension implementation

This is the problem. You’re not overriding the protocol extension version, 
you’re just shadowing it for the purposes of compile-time name lookup. Note 
that if you add the ‘override’ keyword here, the compiler complains because 
there’s nothing in the base class to override.

At least in the case where the conformance is defined in the same module as the 
type, we could add new vtable entries to the class to allow the protocol 
extension method to be overridden in subclasses. But that’s not implemented yet.

Slava

>   return "B"
>   }
> }
> 
> let b = B()
> b.item // returns “B”
> 
> No surprise there either. B specialises 'item' so that’s what gets used. 
> But...
> 
> b.usedItem // returns “P” !!?
> 
> I can hear you thinking "That's because 'usedItem' is being statically 
> dispatched, since it's not declared in the protocol" but adding a declaration 
> for 'usedItem' to the protocol doesn't help! I'll get to that in a moment.
> 
> Now consider class C, which is similar to B but also overrides A’s 
> implementation of 'usedItem' to do, well, exactly what A does (at least 
> syntactically):
> 
> class C: A {
>   var item: String {
>   return "C"
>   }
>   override var usedItem: String {
>   return item
>   }
> }
> 
> let c = C()
> c.item
> c.usedItem
> 
> Now we get “C” for both calls, as desired, but having to add the override 
> keyword just for this is ugly at best. What, then, if we did add a 
> declaration for 'usedItem' to the protocol?
> 
> protocol P {
>   var item: String { get }
>   var usedItem: String { get }
> }
> 
> extension P {
>   var item: String {
>   return "P"
>   }
>   var usedItem: String {
>   return item
>   }
> }
> 
> class A: P {
> }
> 
> let a = A()
> a.item // returns “P"
> a.usedItem // returns “P"
> 
> No surprises here.
> 
> class B: A {
>   var item: String {
>   return "B"
>   }
> }
> 
> let b = B()
> b.item // returns “B”
> b.usedItem // still returns “P” !!
> 
> The result is still "P", even though 'usedItem' is now being dynamically 
> dispatched. Yes, B doesn't specialise the protocol extension's implementation 
> of 'usedItem' so there really isn't an implementation of that to dynamically 
> dispatch but =that shouldn't matter= (yet it does). B does specialise 'item', 
> though, so *that* should be dynamically dispatched (since it is declared in 
> the protocol). And it is, if called directly, but if it's called from within 
> the protocol extension's default implementation of another dynamically 
> dispatched invocation that isn't itself specialised, then it's not.
> 
> Of course, there's a solution similar to that of class C but, like that 
> solution, this one also involves the presence of extra code that is 
> syntactially identical to the default implementation.
> 
> class C: A {
>   var item: String {
>   return "C"
>   }
>   var usedItem: String {
>   return item
>   }
> }
> 
> let c = C()
> c.item // returns “C”
> c.usedItem // now returns “C”, as desired.
> 
> What I find most surprising is that the static or dynamic dispatch behaviour 
> of a method in the protocol extension is not determined solely by the absence 
> or presence of its declaration in the protocol but also by whether or not 
> conforming types actually have a specialised implementation. As I pointed out 
> above, that second bit should not matter, yet it does. It seems to me that 
> this is a bug in how protocol extensions work but I might be wrong about that.
> 
> Any thoughts?
> 
> Thanks.
> Wagner
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Exclamation mark's in swift parameter listings?

2017-01-18 Thread Slava Pestov via swift-users
Boxing usually refers to out-of-line allocation of values on the heap. For 
example, values of protocol type (as well as Any) will box their payload, 
depending on size.

Slava

> On Jan 18, 2017, at 10:53 PM, Rien  wrote:
> 
> Thanks Slava,
> 
> Then my memory wasn’t that bad. This is indeed what I was thinking of, but I 
> should not have referred to it as ‘boxing’ ?
> 
> Regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Swiftrien
> Project: http://swiftfire.nl
> 
> 
> 
> 
>> On 19 Jan 2017, at 05:57, Slava Pestov  wrote:
>> 
>> For what it’s worth, if T is a reference type or Unsafe*Pointer, then T and 
>> Optional have the same exact representation in memory.
>> 
>> The compiler is smart enough to know that a non-optional pointer can never 
>> be NULL, so a NULL value of the underlying type can be used to unambiguously 
>> encode the ‘none’ case. This is not the case with Optional for 
>> example, where every bit pattern represents a potentially valid NSRect 
>> value, so Optional has to add an extra tag byte to distinguish the 
>> two enum cases from each other.
>> 
>> Slava
>> 
>>> On Jan 10, 2017, at 9:52 AM, Rien via swift-users  
>>> wrote:
>>> 
>>> I stand corrected.
>>> 
>>> I do/did think that there is a difference in the way it handles pointers 
>>> optionals and other optionals, but I now realise that even that could not 
>>> be the case.
>>> So please ignore the last line in my previous post.
>>> 
>>> The rest still stand ;-)
>>> 
>>> Regards,
>>> Rien
>>> 
>>> Site: http://balancingrock.nl
>>> Blog: http://swiftrien.blogspot.com
>>> Github: http://github.com/Swiftrien
>>> Project: http://swiftfire.nl
>>> 
>>> 
>>> 
>>> 
 On 10 Jan 2017, at 18:14, Joe Groff  wrote:
 
 
> On Jan 9, 2017, at 11:19 PM, Rien via swift-users  
> wrote:
> 
> It means that a call to that function with an optional will unwrap the 
> optional before it is used.
> 
> That is quite neat when dealing with C-API’s because often you will 
> receive a pointer from a C-function which is optional to account for the 
> fact that it can be NULL (= nil).
> By using a forced unwrapped input parameter you are saved the trouble of 
> unwrapping all these pointers when using them as input for other C-APIs.
> 
> In short, it makes it easier to interface with C-API’s.
> 
> Note that there is some under-the-hood magic going on because a C-pointer 
> is an unboxed value, while a ‘normal’ optional is a boxed value.
 
 Optionals are never boxed.
 
 -Joe
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-users
>> 
> 

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


Re: [swift-users] make a static/class method return type be the subclass it is called with

2017-01-10 Thread Slava Pestov via swift-users

> On Jan 9, 2017, at 11:59 PM, Pierre Monod-Broca via swift-users 
>  wrote:
> 
> Hi again,
> 
> You might want to look at Self requirement in protocols for exemple:
> protocol P {
>  func items(/*...*/) -> [Self]
> }
> class C: P {
>  func items(/*...*/) -> [C] {
>...
>  }
> }

FWIW, this requires that ‘C’ is final. Otherwise, a subclass ‘D’ of ‘C’ won’t 
satisfy the requirement, because C.items() still returns a ‘C’ and not a ‘D’.

> 
> However it might not always work as you expect.
> 
> I can't say which is the better. Using associated type might be more 
> flexible. 
> 
> Pierre
> 
>> Le 5 janv. 2017 à 21:10, davel...@mac.com a écrit :
>> 
>> Yes, it does seem to work. I just wondered if there was a better way to do 
>> it. Perhaps by writing the method in a base class (but I couldn't get that 
>> to work) instead of using an extension. Then I could just inherit from that 
>> base class rather than needing to write:
>> 
>> extension Event: DDRCoreData {
>> typealias Entity = Event
>> }
>> 
>> in addition to class Event: NSManagedObject . . .
>> 
>> Yes, I know in Xcode 8, that last part can now be written for you.
>> 
>> Again, if this is the "right way to do it", I'm ok with that, I just 
>> wondered if there is a better way to do it.
>> 
>> Thanks,
>> Dave Reed
>> 
>> 
>>> On Jan 5, 2017, at 2:35 PM, Pierre Monod-Broca  
>>> wrote:
>>> 
>>> Hello,
>>> 
>>> It looks that you have what you wanted because Event.Entity is an alias of 
>>> Event. 
>>> 
>>> Pierre
>>> 
 Le 5 janv. 2017 à 16:47, Dave Reed via swift-users  
 a écrit :
 
 Is there a way to make a static or class method specify the return type be 
 the actual class it is called with?
 
 The example code below using protocols/extensions mostly works (the type 
 is [Event.Entity] not [Event] but it seems to work.
 
 If I try to make DDRCoreData a base class and Event subclass it, I'm only 
 able to get the return type to be [DDRCoreData], not [Event] when I call 
 it with Event.items(in: moc)
 
 Here is the code that mostly works using protocols. Is there a better way 
 to do this?
 
 protocol DDRCoreData {
 associatedtype Entity: NSManagedObject
 
 static func items(in context: NSManagedObjectContext, matching predicate: 
 NSPredicate?, sortedBy sorters: [NSSortDescriptor]?) -> [Entity]
 }
 
 extension DDRCoreData {
 static func items(in context: NSManagedObjectContext, matching predicate: 
 NSPredicate? = nil, sortedBy sorters: [NSSortDescriptor]? = nil) -> 
 [Entity] {
 var items: [Entity] = []
 context.performAndWait {
 let fetchRequest: NSFetchRequest = Entity.fetchRequest() 
 as! NSFetchRequest
 fetchRequest.predicate = predicate
 fetchRequest.sortDescriptors = sorters
 do {
 items = try fetchRequest.execute() as [Entity]
 } catch {
 
 }
 }
 return items
 }
 }
 
 @objc(Event)
 public class Event: NSManagedObject {
 
 }
 
 extension Event: DDRCoreData {
 typealias Entity = Event
 }
 
 // compiler says items is of type [Event.Entity]
 let items = Event.items(in: controller.managedObjectContext!)
 
 Thanks,
 Dave Reed
 
 
 ___
 swift-users mailing list
 swift-users@swift.org
 https://lists.swift.org/mailman/listinfo/swift-users
>> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Is it possible to compile swift code to dynamic library?

2017-01-09 Thread Slava Pestov via swift-users
Right now, we don’t have an ‘official’ way to expose Swift APIs to C. However 
there is the completely unsupported and subject to change or removal at any 
time @_cdecl attribute. Eg,

@_cdecl(“bar_foo") public func foo(x: Int) -> Int { return x }

This defines a function callable from C as:

extern int bar_foo(int x);

I don’t suggest using this for anything serious because it has some known 
problems and it’s going to change before it’s final (hence it’s undocumented, 
underscored status).

If someone wants a starter project, finishing off @_cdecl (and getting it 
through swift-evolution) would be really cool. My understanding is that the 
main thing lacking is untangling some of the diagnostics code to consider C and 
Objective-C separately, since C is more restrictive. We could even add support 
to PrintAsObjC for generating pure-C “bridging headers”. :-)

As for actually building a shared library, that depends on if you’re using 
Xcode or command line, Mac or Linux, etc. If you’re on the command line take a 
look at the -emit-library flag to the swiftc driver.

Slava

> On Jan 9, 2017, at 5:57 PM, Zheng Ping via swift-users 
>  wrote:
> 
> I want to compile swift code to dynamic library, and I can link this dynamic 
> library to my C project. I don't know whether is it possible? Or whether I 
> can do this in the future?
> 
> -- 
> with kind regards
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] inout generic struct parameter error

2017-01-01 Thread Slava Pestov via swift-users
Nice catch. Here’s a minimal test case:

struct G {}

func f1(_: inout G) {}
func f2(_: inout G) {}

func g1(t: G) {
  let _ = f1() // cannot pass immutable value as inout argument: 't' is a 
'let' constant
}

func g2(t: G) {
  let _ = f2() // cannot convert value of type 'G' to expected argument 
type 'G<_>'
}

func g3(t: G) {
  let _ = f2() // cannot convert value of type 'G' to expected argument 
type 'G<_>'
}

In the second two cases, f2() is called, which has a generic type. Since the 
constraint system could not be solved, CSDiag won’t have a type substitution 
for T so the unresolved type prints as _ in the diagnostic. It looks like we 
bail out before checking if the failure is due to an ‘inout’ mismatch, and 
produce the bad generic diagnostic instead of the more specific one.

I filed https://bugs.swift.org/browse/SR-3525 
 if anyone wants to take a look.

Slava

> On Jan 1, 2017, at 4:52 PM, Ben Cohen via swift-users  
> wrote:
> 
> Hi Georgios,
> 
> Yes, that isn’t the best of error messages.
> 
> The problem is that makeIterator() is not a mutating function, so inside it 
> all properties are treated as immutable. This means you aren’t allowed to 
> pass them into functions as inout arguments. It’s essentially the same as 
> this:
> 
> func takesInout(i: inout Int) { i += 1 }
> 
> struct S {
> var x: Int
> func nonmutating() {
> takesInout(i: )
> }
> }
> // Error: Cannot pass immutable value as inout argument: 'self' is immutable
> // Fix-it: Mark method mutating to make 'self' mutable
> 
> Ideally you’d get an error message along these lines for your case but it 
> looks like it’s failing.
> 
> So, you might consider making makeIterator mutating like the Fix-it suggests, 
> which would allow you to pass its members as inout arguments:
> 
> mutating public func makeIterator() -> WeakArrayIterator {
> 
> But if you do this you will get a different compiler error, because your 
> struct will no longer conform to Sequence, which requires makeIterator to be 
> non-mutating. This is important, especially assuming your array is eventually 
> going to conform to Collection as well. One of the requirements of 
> collections is that they give an accurate count, but in the case of your 
> array, the count returned might be different (greater) than the number of 
> elements returned when you actually iterate the array, and this is not 
> allowed (you may find that some standard library functions will trap when 
> they discover that this has happened).
> 
> HTH,
> Ben
> 
> 
>> On Jan 1, 2017, at 10:48 AM, Georgios Moschovitis via swift-users 
>> > wrote:
>> 
>> While getting my feet wet with Swift, I am still surprised with type-system 
>> ‘quirks’ here and there.
>> 
>> I tried to implement a simple array of weak references:
>> 
>> public struct WeakArrayIterator: IteratorProtocol {
>> var array: [Weak]
>> var index = 0
>> 
>> init(_ array: [Weak]) {
>> self.array = array
>> }
>> 
>> mutating public func next() -> T? {
>> while index < array.count && array[index].value == nil {
>> // Remove weak references invalidated by ARC.
>> array.remove(at: index)
>> }
>> 
>> if index < array.count {
>> let value = array[index].value
>> index += 1
>> return value
>> } else {
>> return nil
>> }
>> }
>> }
>> 
>> public struct WeakArray: Sequence {
>> var weakRefs: [Weak]
>> 
>> init() {
>> weakRefs = []
>> }
>> 
>> public var count: Int {
>> return weakRefs.count
>> }
>> 
>> public subscript(index: Int) -> T? {
>> get {
>> return weakRefs[index].value
>> }
>> 
>> set(value) {
>> weakRefs[index] = Weak(value!)
>> }
>> }
>> 
>> mutating public func append(_ value: T) {
>> weakRefs.append(Weak(value))
>> }
>> 
>> @discardableResult
>> mutating func remove(at index: Int) -> T? {
>> return weakRefs.remove(at: index).value
>> }
>> 
>> public func makeIterator() -> WeakArrayIterator {
>> return WeakArrayIterator(weakRefs)
>> }
>> }
>> 
>> This kinda works but because we pass a struct at:
>> 
>> return WeakArrayIterator(weakRefs)
>> 
>> the ‘garbage collection’ at:
>> 
>> // Remove weak references invalidated by ARC.
>> array.remove(at: index)
>> 
>> doesn’t affect the original array.
>> 
>> I tried changing to this:
>> 
>> public struct WeakArrayIterator: IteratorProtocol {
>> ...
>> init(_ array: inout [Weak]) {
>> self.array = array
>> }return WeakArrayIterator()
>> …
>> 
>> public struct WeakArray: Sequence {
>> return WeakArrayIterator()
>> 
>> but I get this strange (to me) error:

Re: [swift-users] Compiler crashes while resolving generics constraints

2016-12-26 Thread Slava Pestov via swift-users
The Swift 3 crash is definitely a compiler bug — the compiler should never 
crash, even with invalid code. However it looks like we fixed it already, and 
the latest snapshot produces a compile error instead. Let us know if you need 
any more help!

Slava

> On Dec 26, 2016, at 2:56 PM, Игорь Никитин <devni...@icloud.com> wrote:
> 
> Now I’m not sure that it’s a compiler bug.
> Maybe I not provide enough info of the type system or whatever else
> 
> Thanks for the help!
> 
>> 26 дек. 2016 г., в 22:49, Slava Pestov via swift-users 
>> <swift-users@swift.org <mailto:swift-users@swift.org>> написал(а):
>> 
>>> 
>>> On Dec 26, 2016, at 2:30 PM, Игорь Никитин <devni...@icloud.com 
>>> <mailto:devni...@icloud.com>> wrote:
>>> 
>>> Hello!
>>> 
>>> Here is a class that uses all of this protocols: 
>>> https://gist.github.com/rabbitinspace/a88410d778e5ac955ee88bdfede6e00b 
>>> <https://gist.github.com/rabbitinspace/a88410d778e5ac955ee88bdfede6e00b>
>>> Line 19
>>> 
>>> Latest Xcode gives me this log: 
>>> https://gist.github.com/rabbitinspace/6cb5ebd536a81b0b1cc6b0fadbabbe77 
>>> <https://gist.github.com/rabbitinspace/6cb5ebd536a81b0b1cc6b0fadbabbe77>
>>> It’s a compiler crash, I think
>>> 
>>> While the latest dev swift snapshot produces a build error: 
>>> https://gist.github.com/rabbitinspace/944a62efc18432baf781e368a1023b87 
>>> <https://gist.github.com/rabbitinspace/944a62efc18432baf781e368a1023b87>
>>> Shortly:
>>> cannot invoke 'authenticationService' with an argument list of type 
>>> '(for: Remote.Type)’
>>> expected an argument list of type '(for: Remote.Type)’
>>> 
>>> I can build it with the latest dev snapshot (Xcode still can't) if I will 
>>> constraint generic types in AuthController class:
>>> Can’t compile: 
>>>final class AuthController>> RemoteAuthenticationServiceBuilder>
>>> 
>>> This is compiles successfully:
>>>final class AuthController>> RemoteAuthenticationServiceBuilder> 
>>>where Builder.Service.Remote == Remote 
>>> 
>> 
>> It seems this is the correct fix — the compile error is obtuse, but it 
>> sounds like it’s talking about the two different types (both named ‘Remote’).
>> 
>> If you feel this behavior is in error, do you mind filing a JIRA bug?
>> 
>> Slava
>> 
>>> 
>>> 
>>>> 25 дек. 2016 г., в 23:50, Slava Pestov via swift-users 
>>>> <swift-users@swift.org <mailto:swift-users@swift.org>> написал(а):
>>>> 
>>>> Hi Igor,
>>>> 
>>>> Your example is not self-contained, so I added the following definitions:
>>>> 
>>>> struct URI {}
>>>> 
>>>> struct App {
>>>>   class Remote {
>>>> struct Credentials {} 
>>>>   }
>>>> }
>>>> 
>>>> struct RemoteUser {}
>>>> 
>>>> protocol ResponseRepresentable {}
>>>> 
>>>> protocol RemoteCredentials {}
>>>> 
>>>> Unfortunately, this makes the code compile in both Swift 3.0 and the 
>>>> latest code built from GitHub, even with the ‘where’ part uncommented, so 
>>>> I suspect we’ll need a larger testcase to reproduce the original issue.
>>>> 
>>>> However from looking at the code, what you’re doing is adding a 
>>>> requirement to an associated type of the ‘Self’ generic parameter, which 
>>>> Swift 3.0 did not model properly, but it is one of the things we addressed 
>>>> in some recent refactoring work.
>>>> 
>>>> Could you try the latest development snapshot from swift.org 
>>>> <http://swift.org/> and let us know if it solves your problem?
>>>> 
>>>> Slava
>>>> 
>>>>> On Dec 25, 2016, at 1:05 PM, Игорь Никитин via swift-users 
>>>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>>>> 
>>>>> Hello!
>>>>> 
>>>>> I have few protocols with associated types:
>>>>> protocol Remote {
>>>>> associatedtype Credentials: RemoteCredentials
>>>>> 
>>>>> static var url: URI { get }
>>>>> static var name: String { get }
>>>>> static var credentials: Credentials.Type { get }
>>>>> }
>>>>> proto

Re: [swift-users] Compiler crashes while resolving generics constraints

2016-12-26 Thread Slava Pestov via swift-users

> On Dec 26, 2016, at 2:30 PM, Игорь Никитин <devni...@icloud.com> wrote:
> 
> Hello!
> 
> Here is a class that uses all of this protocols: 
> https://gist.github.com/rabbitinspace/a88410d778e5ac955ee88bdfede6e00b 
> <https://gist.github.com/rabbitinspace/a88410d778e5ac955ee88bdfede6e00b>
> Line 19
> 
> Latest Xcode gives me this log: 
> https://gist.github.com/rabbitinspace/6cb5ebd536a81b0b1cc6b0fadbabbe77 
> <https://gist.github.com/rabbitinspace/6cb5ebd536a81b0b1cc6b0fadbabbe77>
> It’s a compiler crash, I think
> 
> While the latest dev swift snapshot produces a build error: 
> https://gist.github.com/rabbitinspace/944a62efc18432baf781e368a1023b87 
> <https://gist.github.com/rabbitinspace/944a62efc18432baf781e368a1023b87>
> Shortly:
>   cannot invoke 'authenticationService' with an argument list of type 
> '(for: Remote.Type)’
>   expected an argument list of type '(for: Remote.Type)’
> 
> I can build it with the latest dev snapshot (Xcode still can't) if I will 
> constraint generic types in AuthController class:
> Can’t compile: 
>final class AuthController RemoteAuthenticationServiceBuilder>
> 
> This is compiles successfully:
>final class AuthController RemoteAuthenticationServiceBuilder> 
>where Builder.Service.Remote == Remote 
> 

It seems this is the correct fix — the compile error is obtuse, but it sounds 
like it’s talking about the two different types (both named ‘Remote’).

If you feel this behavior is in error, do you mind filing a JIRA bug?

Slava

> 
> 
>> 25 дек. 2016 г., в 23:50, Slava Pestov via swift-users 
>> <swift-users@swift.org <mailto:swift-users@swift.org>> написал(а):
>> 
>> Hi Igor,
>> 
>> Your example is not self-contained, so I added the following definitions:
>> 
>> struct URI {}
>> 
>> struct App {
>>   class Remote {
>> struct Credentials {} 
>>   }
>> }
>> 
>> struct RemoteUser {}
>> 
>> protocol ResponseRepresentable {}
>> 
>> protocol RemoteCredentials {}
>> 
>> Unfortunately, this makes the code compile in both Swift 3.0 and the latest 
>> code built from GitHub, even with the ‘where’ part uncommented, so I suspect 
>> we’ll need a larger testcase to reproduce the original issue.
>> 
>> However from looking at the code, what you’re doing is adding a requirement 
>> to an associated type of the ‘Self’ generic parameter, which Swift 3.0 did 
>> not model properly, but it is one of the things we addressed in some recent 
>> refactoring work.
>> 
>> Could you try the latest development snapshot from swift.org 
>> <http://swift.org/> and let us know if it solves your problem?
>> 
>> Slava
>> 
>>> On Dec 25, 2016, at 1:05 PM, Игорь Никитин via swift-users 
>>> <swift-users@swift.org <mailto:swift-users@swift.org>> wrote:
>>> 
>>> Hello!
>>> 
>>> I have few protocols with associated types:
>>> protocol Remote {
>>> associatedtype Credentials: RemoteCredentials
>>> 
>>> static var url: URI { get }
>>> static var name: String { get }
>>> static var credentials: Credentials.Type { get }
>>> }
>>> protocol RemoteAuthenticating {
>>> associatedtype Remote: App.Remote
>>> 
>>> func authenticate(with credentials: Remote.Credentials) throws -> 
>>> (RemoteUser, ResponseRepresentable?)
>>> }
>>> protocol RemoteAuthenticationServiceBuilder {
>>> associatedtype Service: RemoteAuthenticating
>>> 
>>> // TODO: `Service.Remote` should be constrained to `Remote` but 
>>> compiler crashes
>>> func authenticationService(for: Remote.Type) -> 
>>> Service? // where Service.Remote == Remote
>>> }
>>> It works fine until I uncomment the last where statement
>>> If I trying to constraint Service.Remote type compiler will crash with 
>>> segfault 11
>>> I can guess that it's a compiler bug, but maybe I’m using generics in wrong 
>>> way?
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org <mailto:swift-users@swift.org>
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> <https://lists.swift.org/mailman/listinfo/swift-users>
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org <mailto:swift-users@swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users
> 

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


Re: [swift-users] Weird protocol behaviour.

2016-12-25 Thread Slava Pestov via swift-users

> On Dec 22, 2016, at 4:43 PM, Howard Lovatt via swift-users 
>  wrote:
> 
> The following variation works:
> 
> protocol P {}
> 
> class P1:P {}
> 
> class X:P1 {}
> 
> func foo(_ x:A) {}
> 
> func bar() {
> //let x = X() // this compiles
> let x = X() as P1 // this does not compile. Why?
> foo(x)
> }
> 
> Which adds credence to the bug theory.

It’s an intentional limitation. Protocols do not conform to themselves. Lifting 
the restriction would be difficult to do efficiently given our representation 
of generics and protocols at runtime.

Slava

> 
> Note two changes: 1. two levels of inheritance and 2. change to classes. If 
> you do two levels using protocols it doesn't work if you use either classes 
> or structs.
> 
> 
>   -- Howard.
> 
> On 23 December 2016 at 07:29, Kevin Nattinger  > wrote:
> I recall seeing a request on the -evolution list for something like `T := X` 
> to indicate it could be X itself or anything inheriting / implementing it, so 
> it’s certainly known behavior, if not desired. IMO it’s a bug and `:` should 
> be fixed to include the root type, whether or not that requires a discussion 
> on -evolution.
> 
>> On Dec 22, 2016, at 2:17 PM, Howard Lovatt via swift-users 
>> > wrote:
>> 
>> I suspect a compiler bug since A is a P. The equivalent in Java works:
>> 
>> interface P {}
>> class X implements P {}
>>  
>>  void foo(A x) {}
>>  
>> void bar() {
>> final P x = new X();
>> foo(x);
>> }
>> 
>> -- Howard. 
>> 
>> On 23 Dec 2016, at 3:19 am, Rien via swift-users > > wrote:
>> 
>>> IMO the error message says it all:
>>> 
>>> Playground execution failed: error: MyPlayground8.playground:9:5: error: 
>>> cannot invoke 'foo' with an argument list of type '(P)'
>>>foo(x)
>>>^
>>> 
>>> MyPlayground8.playground:9:5: note: expected an argument list of type '(A)'
>>>foo(x)
>>>^
>>> 
>>> I.e. you are passing in a protocol while the function is specified for a 
>>> type.
>>> Said other way: On which data do you expect the protocol to operate?
>>> 
>>> Regards,
>>> Rien
>>> 
>>> Site: http://balancingrock.nl 
>>> Blog: http://swiftrien.blogspot.com 
>>> Github: http://github.com/Swiftrien 
>>> Project: http://swiftfire.nl 
>>> 
>>> 
>>> 
>>> 
 On 22 Dec 2016, at 17:05, Mikhail Seriukov via swift-users 
 > wrote:
 
 Hello community! I' wondering if somebody can explain this to me.
 Please take look at the snippet.
 
 protocol P {}
 struct X:P {}
 
 func foo(_ x:A) {}
 
 func bar() {
//let x = X() // this compiles
let x = X() as P // this does not compile. Why?
foo(x)
 }
 
 I expect the both cases to work though. But only first works? And I do not 
 understand why.
 My coworkers said that it is a compiler bug, but I'm not shure it is.
 Thanks for the help.
 ___
 swift-users mailing list
 swift-users@swift.org 
 https://lists.swift.org/mailman/listinfo/swift-users 
 
>>> 
>>> ___
>>> swift-users mailing list
>>> swift-users@swift.org 
>>> https://lists.swift.org/mailman/listinfo/swift-users 
>>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org 
>> https://lists.swift.org/mailman/listinfo/swift-users 
>> 
> 
> 
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Element vs. Iterator.Element

2016-11-02 Thread Slava Pestov via swift-users
I don’t remember the details, but IIRC ‘Iterator’ is an inferred associated 
type on Array, so it cannot appear in the ‘where’ clause of an extension. This 
is a known limitation of the name lookup code — presently it cannot recur into 
associated type inference due to circularity. We plan on addressing this with 
the ‘iterative declaration checker’, but that is some ways off.

Slava

> On Oct 31, 2016, at 5:28 AM, Toni Suter via swift-users 
>  wrote:
> 
> Hi,
> 
> This extension on Array works as expected:
> 
> extension Array where Element: CustomStringConvertible {
> func f(_ x: Element) -> String {
> return x.description
> }
> }
> 
> But when I use Iterator.Element instead, I get an error message (error: value 
> of type 'Element' has no member 'description'):
> 
> extension Array where Iterator.Element: CustomStringConvertible {
> func f(_ x: Iterator.Element) -> String {
> return x.description
> }
> }
> 
> I assume this is a type checker bug, but before I report it, I wanted to make 
> sure that that’s really the case. Or is there a difference between Element and
> Iterator.Element?
> 
> Thanks and best regards,
> Toni
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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


Re: [swift-users] Swift in bare-metal embedded programming/Swift runtime

2016-08-16 Thread Slava Pestov via swift-users

> On Aug 15, 2016, at 3:36 PM, Rick Mann  wrote:
> 
> Well, even C++ requires some amount of run time. On a larger MCU, the runtime 
> shouldn't be a problem at all. What I want to do is minimize the amount of OS 
> I have to implement. For example, using newlib 
> (https://sourceware.org/newlib/ ), I can stub 
> out 20-odd functions, and everything gets statically linked into a monolithic 
> block of code that is a combination of my code, the runtime, and those 20-odd 
> function stubs. A special chunk of code, usually containing assembly 
> language, ensures the processor and MMU are properly set up just after boot, 
> and you're off to the races.
> 
> I imagine there will be additional burden to support threading and GCD (which 
> would be nice to have). But before that, supporting synchronization and 
> interrupt routines.
> 
> Ah, interrupt routines. Is there any way to mark a function as "naked" in 
> Swift? How would I request that feature?

This would require significant design work. The main problem is that the Swift 
runtime is not re-entrant, because typical malloc() implementations are not 
re-entrant, and also because of how metadata caching uses locks. So even if you 
could emit a function with the right calling convention, it wouldn't be safe to 
use as an interrupt handler.

Slava

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


Re: [swift-users] Swift in bare-metal embedded programming/Swift runtime

2016-08-11 Thread Slava Pestov via swift-users
Even if you take care not to create class instances, the compiler emits many 
calls to runtime functions to implement features such as generics, casts and 
existentials. It is possible to write code where a large number of runtime 
calls are optimized away, but I don’t think they can be eliminated completely.

If anyone is interested in taking this on as a community project, it would be a 
fair amount of work, but I think the first step could be to add compiler flags 
where calls to runtime functions become diagnostics. Again though, I’m not sure 
how much effort it would take to eliminate them completely.

Slava

> On Aug 10, 2016, at 3:28 AM, David Sweeris via swift-users 
>  wrote:
> 
> There's definitely a runtime, but I *think* you can avoid actually using it 
> by being very careful with your data structures. ARC means that classes 
> obviously trigger it, and I think it *might* be involved resizing arrays and 
> strings (they do some tricks behind the scenes, but I can't remember what).
> 
> So... only use structs and don't resize anything? I'm not sure... I think 
> there might be some cases where protocols or indirect enums get stored as 
> references, and that might involve the runtime as well.
> 
> Maybe you should go over to the evolution list and suggest a "no runtime" 
> compiler flag or source code annotation, which disallows anything which would 
> use the runtime. I believe there could be advantages outside of running on 
> bare-metal, since you could use it to get the compiler to yell at you for 
> doing overhead-inducing stuff in a loop, for example. 
> 
> Anyway, best of luck :-)
> 
> - Dave Sweeris
> 
>> On Aug 9, 2016, at 15:10, Rick Mann via swift-users  
>> wrote:
>> 
>> Is it possible to use Swift for bare-metal programming on embedded devices? 
>> These devices usually have memory-mapped registers that are read and written 
>> to affect the operation of the device. Some can be quite small (e.g. 8-bit 
>> registers, simple single physical memory address space), and others quite 
>> robust (full 32- or 64-bit machines with MMUs, etc.).
>> 
>> But bare metal development for all of them starts with emitting code with 
>> "raw" packaging (no Mach or ELF headers, etc.), and the ability to read and 
>> write specific memory addresses.
>> 
>> For the smaller devices, runtime library overhead is a concern (mostly due 
>> to code size). Is it possible to write swift code with no runtime library? I 
>> think this is possible in Rust (came up on another list).
>> 
>> Most such development is done in C, and there is always some form of library 
>> to take on some of the standard library tasks and stub out basic IO, as well 
>> as filling in gaps for larger variable sizes not directly supported by the 
>> hardware.
>> 
>> I imagine there's some runtime support for ARC, although maybe that's 
>> handled entirely in the compilation phase?
>> 
>> Anyway, I'd appreciate someone more knowledgable letting me know if this is 
>> something I should experiment with. Thanks!
>> 
>> -- 
>> Rick Mann
>> rm...@latencyzero.com
>> 
>> 
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

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