[swift-users] struct property changing calls didSet of the Struct each time, but class won't

2017-11-13 Thread Zhao Xin via swift-users
Hi everyone,

See below codes,

//: Playground - noun: a place where people can play


import Foundation


struct Foo {

var bar = 0

}


class A {

var foo = Foo() {

didSet {

print("foo changed")

}

}

}


let a = A()


for i in 1...5 {

a.foo.bar = i

}


// prints five times

// foo changed

// foo changed

// foo changed

// foo changed

// foo changed


If I change `struct Foo` to `class Foo`, nothing will happen.

My code depends on the class version didSet but I used the struct version.
It took me a long time to debug this out. Is this a knowledge that has been
well known already?

Xcode 9.1, Swift 4.0.2


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


Re: [swift-users] Swift 4 "Cannot use mutating member on immutable value: 'self' is immutable"

2017-09-13 Thread Zhao Xin via swift-users
I begin to think it is related to how you `popFirst()` implemented. Check
it or post it here.

Zhao Xin

On Thu, Sep 14, 2017 at 9:36 AM, Roderick Mann 
wrote:

> Yeah, that's not it. I made the change you suggested, I get the same error.
>
> > On Sep 13, 2017, at 18:11 , Zhao Xin  wrote:
> >
> > Change `self` to `ModelFetcher`. You are calling a class static
> property, not a class instance property.
> >
> > Zhao Xin
> >
> > On Thu, Sep 14, 2017 at 8:37 AM, Rick Mann via swift-users <
> swift-users@swift.org> wrote:
> > Moving to Swift 4, I'm running into an issue for which I can't seem to
> find an answer in google:
> >
> > "Cannot use mutating member on immutable value: 'self' is immutable"
> >
> > The code looks like:
> >
> > class
> > ModelFetcher : NSObject, URLSessionDelegate
> > {
> > ...
> > static  let managerDispatchQueue=
>  DispatchQueue(label: "Model Download Manager Queue")
> > static  var pendingFetchers =
>  [ModelFetcher]()
> > static  var currentFetcher: ModelFetcher?
> >
> > class
> > func
> > startNextFetcher()
> > {
> > self.managerDispatchQueue.async
> > {
> > guard
> > self.currentFetcher == nil,
> > let mf = self.pendingFetchers.popFirst()
> >   ^ error:
> cannot use mutating member on immutable value: 'self' is immutable
> > else
> > {
> > return
> > }
> >
> > self.currentFetcher = mf
> > mf.start()
> > }
> > }
> > ...
> > }
> >
> > This code compiled fine in Xcode 8, or in Xcode 9/Swift 3.2 as a
> monolithic app (the error shows up when this code is factored into a
> framework). Other mutating references to self seem to compile okay (e.g.
> "self.currentFetcher = nil" or "self.pendingFetchers.remove(at: idx)").
> Not sure what's special about this one.
> >
> >
> > --
> > Rick Mann
> > rm...@latencyzero.com
> >
> >
> > ___
> > swift-users mailing list
> > swift-users@swift.org
> > https://lists.swift.org/mailman/listinfo/swift-users
> >
>
>
> --
> Rick Mann
> rm...@latencyzero.com
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Foundation bug or indended?

2017-09-04 Thread Zhao Xin via swift-users
It is intended.
The swift version you provided is the swift version of Objective-C header.
So they are the same.

Zhao Xin



On Mon, Sep 4, 2017 at 8:01 PM, Adrian Zubarev via swift-users <
swift-users@swift.org> wrote:

> Hi there,
>
> before filing a new issue I would like to ask if this is intended
> behaviour or a bug:
>
> The Foundation class Operation which has it’s roots in Objective-C has a
> few readonly properties like the following one:
>
> @available(iOS 2.0, *)
> open class Operation : NSObject {
> ...
> open var isExecuting: Bool { get }
> ...
> }
>
> On the other hand the Objective-C header looks like this:
>
> NS_CLASS_AVAILABLE(10_5, 2_0)
> @interface NSOperation : NSObject {
> ...
> @property (readonly, getter=isExecuting) BOOL executing;
> ...
> @end
>
> Now I want to create a custom subclass of Operation and override
> isExecuting, everything works fine until I try to create a private stored
> property named executing:
>
> final class TransitionOperation : Operation {
> // error: cannot override with a stored property 'executing'
> private var executing = false
>
> override var isExecuting: Bool {
> ...
> }
> }
>
> I’m a little bit confused here:
>
>- Is this intended behaviour or a bug?
>- The Foundation implemented in Swift is not used for iOS deployment,
>instead the Obj-C one is used right?
>
>
>
>
> ___
> 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 convert to the latest version of Swift because can't find framework module

2017-08-25 Thread Zhao Xin via swift-users
You said you used Xcode command. Did you mean the menu item in Xcode? If
so, you should file a bug on Xcode on bugreport.apple.com.

As far as I know, swift migration guide is planed to be open sourced, but
it is not opened yet. So you should file a bug to Apple.

Zhao Xin​

On Sat, Aug 26, 2017 at 12:27 AM, Bill Cheeseman via swift-users <
swift-users@swift.org> wrote:

> I have a small macOS application with an embedded framework, both written
> in Swift. Each has its own Xcode project in separate locations on my Mac,
> and I use an Xcode workspace to develop and build both at once. I do not
> use CocoaPods or Carthage. My application and framework build and run
> successfully.
>
> When I try to convert to the latest version of Swift using the Xcode
> conversion command, it fails with a "no such module" error for the
> framework.
>
> My online research shows that "no such module" errors have been plaguing
> Xcode developers who use embedded frameworks for several years. A dozen or
> more solutions have been suggested online, and they apparently work in some
> contexts but not in others. None of them work for me.
>
> Has anybody successfully run the Xcode Swift conversion command with an
> embedded framework and everything written in Swift? If so, can you spell
> out the key Xcode setup features that made it work for you?
>
> _
>
> Bill Cheeseman -- wjcheese...@gmail.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


Re: [swift-users] Simultaneous accesses, but modification requires exclusive access

2017-07-24 Thread Zhao Xin via swift-users
You can use serial queue.

class Car {

var helper = Helper()

lazy private var queue = DispatchQueue(label: "my queue")



func test() {

helper.doSomething(f1: f1)

}



func f1() {

queue.async {

_ = self.helper.v1 //Crash - Simultaneous accesses to , but modification requires exclusive access.

}

}

}


Zhao Xin

On Mon, Jul 24, 2017 at 4:22 PM, Quinn "The Eskimo!" via swift-users <
swift-users@swift.org> wrote:

>
> On 24 Jul 2017, at 07:04, somu subscribe via swift-users <
> swift-users@swift.org> wrote:
>
> > - Is there a bug in my code which is being detected in Xcode 9 ?
>
> Yes.  The problem here is that `doSomething(f1:)` is a mutating function,
> so it acts like it takes an `inout` reference to `self.helper`.  That’s one
> mutable reference.  It then calls `Car.f1()`, which tries to get a
> non-mutating reference to exactly the same struct.  This is outlawed in
> Swift 4 as part of the memory ownership effort.
>
> You can read more about the specific change in SE-0176 “Enforce Exclusive
> Access to Memory”.
>
>  proposals/0176-enforce-exclusive-access-to-memory.md>
>
> And the general background to this in the “Ownership Manifesto"
>
> 
>
> > If so could you please explain and suggest an alternate approach / fix ?
>
> It’s hard to offer concrete suggestions without knowing more about your
> high-level goals.  One option is for `doSomething(f1:)` to pass the `inout`
> reference through to `f1`.  For example:
>
> mutating func doSomething(f1: (inout Helper) -> ()) {
> f1()
> }
>
> func f1(h: inout Helper) {
> _ = h.v1  // no crash
> }
>
> but whether that makes sense in your code is for you to decide.
>
> Share and Enjoy
> --
> Quinn "The Eskimo!"
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
>
>
> ___
> 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] matching a protocol value in multiple patterns is not yet supported; use separate cases instead

2017-07-18 Thread Zhao Xin via swift-users
I encounter this error today. "matching a protocol value in multiple
patterns is not yet supported; use separate cases instead"

Sample code:

import Foundation


protocol NameProtocol {

var name:String { get }

}


struct Cat:NameProtocol {

let name:String

}


struct Dog:NameProtocol {

let name: String

}


enum AnimalType {

case catType(cat:NameProtocol)

case dogType(dog:NameProtocol)

}


struct Animal {

let type:AnimalType



func printName() {

switch type {

case .catType(let animal), // matching a protocol value in multiple
patterns is not yet supported; use separate cases instead

.dogType(let animal):

print(animal.name)

}

}

}


let cat = Cat(name: "kitty")

let catType = AnimalType.catType(cat: cat)

let animal = Animal(type: catType)

animal.printName()


I am wondering which proposal this is? And will it be implemented in Swift
4.0? I search the error as keywords, but didn't get the expected results.

Zhao Xin
___
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 Zhao Xin via swift-users
Glad to know the answer. And thank you, Slava and Daniel.​

Zhao Xin

On Wed, Jul 12, 2017 at 7:53 AM, Daniel Dunbar <daniel_dun...@apple.com>
wrote:

>
> On Jul 11, 2017, at 3:55 PM, Zhao Xin via swift-users <
> swift-users@swift.org> 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?
>
>
> No, assuming your handler has been written to not participate in a retain
> cycle (for example, ensuring you use [weak self] if appropriate).
>
>  - Daniel
>
> 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


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

2017-07-11 Thread Zhao Xin via swift-users
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


Re: [swift-users] Should Array's `append(_)` function cause `didSet`?

2017-07-10 Thread Zhao Xin via swift-users
Thanks.

Zhao Xin

On Tue, Jul 11, 2017 at 2:29 AM, Jordan Rose  wrote:

>
>
> On Jul 7, 2017, at 22:50, Marco S Hyman via swift-users <
> swift-users@swift.org> wrote:
>
>
> On Jul 7, 2017, at 9:48 PM, Zhao Xin  wrote:
>
> Thank you very much Marco. But What is  “outside of an initializer” really
> bothers me. **Both** `func bar(keysAndValues:Dictionary)`
> works now. **Are they really outside ?**
>
>
> Uhhh, that is certainly not the results I’d have expected.  Perhaps one of
> the  swift language lawyers can explain.
>
>
> The goal is that once the initializer is completed all accesses will go
> through the setter and therefore trigger willSet/didSet behavior. Since a
> local function can be assigned to a property or something and get called
> later, it has to go through the setter as well. So the rules only apply to
> what's directly in the body of the initializer, not anything nested. (This
> includes closures, even.) It might be worth a bug against us at Apple to
> make this more explicit in the documentation, https://bugreport.apple.com.
>
> We also have a bug where 'defer' can trigger willSet and didSet behavior
> as well, SR-1437 . But that really
> is just a bug.
>
> Jordan
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Filling two type parameters with the same type

2017-07-09 Thread Zhao Xin via swift-users
Sorry Dave, I didn't notice that you said in `extension`. I just put the "where
Source == Displacement" to the original poster's code and the error showed.
My bad.

Zhao Xin

On Sun, Jul 9, 2017 at 1:56 PM, David Sweeris  wrote:

> Hmm... I just tried it in a playground, and it works:
> struct DistortedNoise {
>   let source:Source,
>   displacement:Displacement
>
>
>   init(source:Source, displacement:Displacement)
>   {
> self.source   = source
> self.displacement = displacement
>   }
>
>
> }
> extension DistortedNoise where Source == Displacement {
>   init(source:Source)
>   {
> self.source   = source
> self.displacement = source
>   }
> }
> let foo = DistortedNoise(source: 1) // DistortedNoise
> foo.source // 1
> foo.displacement // 1
>
> That's with Xcode 9b2, using the default Xcode 9.0 toolchain. With Xcode
> 8.3.3 and its default toolchain, the `let foo = ...` line outputs "
> __lldb_expr_2.DistortedNoise" instead of just "DistortedNoise Int>", but that's just a more... I think the word is "qualified"... name
> for the same thing.
>
> - Dave Sweeris
>
>
> On Jul 8, 2017, at 9:39 PM, Zhao Xin  wrote:
>
> No, David, it is now allowed.  "error: same-type requirement makes generic
> parameters 'Source' and 'Displacement' equivalent".
>
> Zhao Xin
>
> On Sun, Jul 9, 2017 at 12:35 PM, David Sweeris via swift-users <
> swift-users@swift.org> wrote:
>
>> You could try putting that init in an extension "where Source ==
>> Displacement"
>>
>> > On Jul 8, 2017, at 21:06, Taylor Swift via swift-users <
>> swift-users@swift.org> wrote:
>> >
>> > I have a type like
>> >
>> > struct DistortedNoise where Source:Noise,
>> Displacement:Noise
>> > {
>> > let source:Source,
>> > displacement:Displacement
>> >
>> > init(source:Source, displacement:Displacement)
>> > {
>> > self.source   = source
>> > self.displacement = displacement
>> > }
>> >
>> > init(source:Source)
>> > {
>> > self.source   = source
>> > self.displacement = source
>> > }
>> > }
>> >
>> > and I get the error
>> >
>> > Compile Swift Module 'Noise' (5 sources)
>> > /home/taylor/noise/sources/noise/noise.swift:576:29: error: 'Source'
>> is not convertible to 'Displacement'
>> > self.displacement = source
>> > ^~
>> >
>> > How do I tell Swift that I want the same type fulfilling both Source
>> and Displacement?
>> >
>> > ___
>> > 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] Filling two type parameters with the same type

2017-07-08 Thread Zhao Xin via swift-users
typealias now = not.

Zhao Xin

On Sun, Jul 9, 2017 at 12:39 PM, Zhao Xin  wrote:

> No, David, it is now allowed.  "error: same-type requirement makes generic
> parameters 'Source' and 'Displacement' equivalent".
>
> Zhao Xin
>
> On Sun, Jul 9, 2017 at 12:35 PM, David Sweeris via swift-users <
> swift-users@swift.org> wrote:
>
>> You could try putting that init in an extension "where Source ==
>> Displacement"
>>
>> > On Jul 8, 2017, at 21:06, Taylor Swift via swift-users <
>> swift-users@swift.org> wrote:
>> >
>> > I have a type like
>> >
>> > struct DistortedNoise where Source:Noise,
>> Displacement:Noise
>> > {
>> > let source:Source,
>> > displacement:Displacement
>> >
>> > init(source:Source, displacement:Displacement)
>> > {
>> > self.source   = source
>> > self.displacement = displacement
>> > }
>> >
>> > init(source:Source)
>> > {
>> > self.source   = source
>> > self.displacement = source
>> > }
>> > }
>> >
>> > and I get the error
>> >
>> > Compile Swift Module 'Noise' (5 sources)
>> > /home/taylor/noise/sources/noise/noise.swift:576:29: error: 'Source'
>> is not convertible to 'Displacement'
>> > self.displacement = source
>> > ^~
>> >
>> > How do I tell Swift that I want the same type fulfilling both Source
>> and Displacement?
>> >
>> > ___
>> > 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] Filling two type parameters with the same type

2017-07-08 Thread Zhao Xin via swift-users
No, David, it is now allowed.  "error: same-type requirement makes generic
parameters 'Source' and 'Displacement' equivalent".

Zhao Xin

On Sun, Jul 9, 2017 at 12:35 PM, David Sweeris via swift-users <
swift-users@swift.org> wrote:

> You could try putting that init in an extension "where Source ==
> Displacement"
>
> > On Jul 8, 2017, at 21:06, Taylor Swift via swift-users <
> swift-users@swift.org> wrote:
> >
> > I have a type like
> >
> > struct DistortedNoise where Source:Noise,
> Displacement:Noise
> > {
> > let source:Source,
> > displacement:Displacement
> >
> > init(source:Source, displacement:Displacement)
> > {
> > self.source   = source
> > self.displacement = displacement
> > }
> >
> > init(source:Source)
> > {
> > self.source   = source
> > self.displacement = source
> > }
> > }
> >
> > and I get the error
> >
> > Compile Swift Module 'Noise' (5 sources)
> > /home/taylor/noise/sources/noise/noise.swift:576:29: error: 'Source' is
> not convertible to 'Displacement'
> > self.displacement = source
> > ^~
> >
> > How do I tell Swift that I want the same type fulfilling both Source and
> Displacement?
> >
> > ___
> > 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] Filling two type parameters with the same type

2017-07-08 Thread Zhao Xin via swift-users
Please try this:

struct DistortedNoise where Source:Noise {

typealias Displacement = Source



let source:Source

let displacement:Displacement



init(source:Source, displacement:Displacement)

{

self.source   = source

self.displacement = displacement

}



init(source:Source)

{

self.source   = source

self.displacement = source

}

}


Zhao Xin

On Sun, Jul 9, 2017 at 12:21 PM, somu subscribe via swift-users <
swift-users@swift.org> wrote:

> Hi Taylor,
>
> If both Source and Displacement are going to be Noise, you could use just
> one placeholder type.
>
> class Noise {}
>
> struct DistortedNoise where Item:Noise
> {
> let source:Item,
> displacement:Item
>
>
> init(source:Item, displacement:Item)
> {
> self.source   = source
> self.displacement = displacement
> }
>
>
> init(source:Item)
> {
> self.source   = source
> self.displacement = source
> }
> }
>
> Regards,
> Muthu
>
> ___
> 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] Should Array's `append(_)` function cause `didSet`?

2017-07-07 Thread Zhao Xin via swift-users
Thank you very much Marco. But What is  “outside of an initializer” really
bothers me. **Both** `func bar(keysAndValues:Dictionary)`
works now. **Are they really outside ?**

struct Foo {

var keys = ["z","y","x"]

{

didSet {

keys.sort()

}

}



init(keysAndValues:Dictionary) {

func bar(keysAndValues:Dictionary) {

keys.append(contentsOf: keysAndValues.keys)

}

bar(keysAndValues:keysAndValues)

}



//private mutating func bar(keysAndValues:Dictionary) {

//keys.append(contentsOf: keysAndValues.keys)

//}

}


let keysAndValues:Dictionary = ["c":"c", "b":"b", "a":"a"]

var foo = Foo(keysAndValues: keysAndValues) // `let foo` is the same result


foo.keys.forEach { print($0) }

/*

 prints

 a

 b

 c

 x

 y

 z

 */


Zhao Xin

On Sat, Jul 8, 2017 at 9:59 AM, Marco S Hyman  wrote:

>
> > init(keysAndValues:Dictionary) {
> > self.keys.append(contentsOf: keysAndValues.keys)
> > }
>
> >
> > Above code doesn't call `didSet` in playground. My .swift file is
> similar and didn't call `didSet` either. However, if without a struct,
> `didSet` is called.
>
> “If you don’t need to compute the property but still need to provide code
> that is run before and after setting a new value, use willSet and didSet.
> The code you provide is run any time the value changes outside of an
> initializer.”
>
> Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3.1).”
> iBooks. https://itun.es/us/jEUH0.l
>
> Note “outside of an initializer”.  didSet and willSet are not called in
> initializers.
>
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Should Array's `append(_)` function cause `didSet`?

2017-07-07 Thread Zhao Xin via swift-users
import Cocoa


struct Foo {

var keys = ["z","y","x"]

{

didSet {

keys.sort()

}

}



init(keysAndValues:Dictionary<String, String>) {

self.keys.append(contentsOf: keysAndValues.keys)

}

}


let keysAndValues:Dictionary<String,String> = ["c":"c", "b":"b", "a":"a"]

var foo = Foo(keysAndValues: keysAndValues) // `let foo` is the same result


foo.keys.forEach { print($0) }

/*

 prints

 z

 y

 x

 b

 c

 a

*/


Above code doesn't call `didSet` in playground. My .swift file is similar
and didn't call `didSet` either. However, if without a struct, `didSet` is
called.


var keys = ["z","y","x"]

{

didSet {

keys.sort()

}

}


let keysAndValues:Dictionary<String,String> = ["c":"c", "b":"b", "a":"a"]

keys.append(contentsOf: keysAndValues.keys)



keys.forEach { print($0) }

/*

 prints

 a

 b

 c

 x

 y

 z

 */



*Xcode 9.0 beta 2 (9M137d)*


*Apple Swift version 4.0 (swiftlang-900.0.45.6 clang-900.0.26)*

*Target: x86_64-apple-macosx10.9*


*macOS Sierra 10.12.5 (16F73)*



Zhao Xin



On Fri, Jul 7, 2017 at 11:52 PM, Jordan Rose <jordan_r...@apple.com> wrote:

> It definitely should. Can you show the code where it wasn’t being called?
>
> Thanks!
> Jordan
>
>
> On Jul 7, 2017, at 00:31, Zhao Xin via swift-users <swift-users@swift.org>
> wrote:
>
> Should Array's `append(_)` functions cause the array's `didSet`?
> In my own test, it did call `didSet` in Playground. But in .swift files,
> it didn't call.
>
> Is this a known bug or something? Which is correct?
>
> Xcode Version 9.0 beta 2 (9M137d)​
>
> swift --version
> Apple Swift version 4.0 (swiftlang-900.0.45.6 clang-900.0.26)
> Target: x86_64-apple-macosx10.9
>
>
> 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


[swift-users] Should Array's `append(_)` function cause `didSet`?

2017-07-07 Thread Zhao Xin via swift-users
Should Array's `append(_)` functions cause the array's `didSet`?
In my own test, it did call `didSet` in Playground. But in .swift files, it
didn't call.

Is this a known bug or something? Which is correct?

Xcode Version 9.0 beta 2 (9M137d)​

swift --version

Apple Swift version 4.0 (swiftlang-900.0.45.6 clang-900.0.26)

Target: x86_64-apple-macosx10.9



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


Re: [swift-users] Design guidelines for computed property vs no-arg method

2017-07-05 Thread Zhao Xin via swift-users
For me, a noun is a property, a verb is a method. So `foo` is a property,
`calculateFoo()` is a method.

For your specific question, `func signum() -> Self` returns `Self`, which
can't be used in property.
`var signum:Self { return self }` will generate an error "'Self' is only
available in a protocol or as the result of a method in a class".
So computed property can't be used here.

Zhao Xin

On Wed, Jul 5, 2017 at 7:57 PM, Jens Persson via swift-users <
swift-users@swift.org> wrote:

> Why is eg the BinaryInteger.signum() a method and not a computed property?
>
> public protocol BinaryInteger … {
> /// Returns `-1` if this value is negative and `1` if it's positive;
> /// otherwise, `0`.
> ///
> /// - Returns: The sign of this number, expressed as an integer of the
> same
> ///   type.
> public func signum() -> Self
> }
>
> The Swift API Design Guidelines doesn't say very much about computed
> property vs method with no arguments, but it seems like signum() violates
> them, no?
>
> /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] can we express "does not conform to a particular protocol"?

2017-07-03 Thread Zhao Xin via swift-users
In my own test, it seams that there is no way to test a type conforms to
Equatable or not.

`Protocol 'Equatable' can only be used as a generic constraint because it
has Self or associated type requirements`

Zhao Xin

On Tue, Jul 4, 2017 at 9:27 AM, David Baraff  wrote:

> No, i want the equality function run if the two types are equatable, and
> false otherwise (even if you might deem them to be the same, e.g. two
> identical sets, because sets do not conform to equatable, or two identical
> classes, becauses classes are not (in general) equatable).
>
> So
>   maybeEqual(3, 3)  // true
>   maybeEqual(3, 4)  // false
>   maybeEqual([1,2,3], [1,2,3])  // false (because arrays are not actual
> equatable)
>
>   let d = [String:Any]()
>   maybeEqual(d, d)  // false because type(d) is not equatable even
> though obviously d is equal to itself
>
>
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] can we express "does not conform to a particular protocol"?

2017-07-03 Thread Zhao Xin via swift-users
You mean `type(of:lhs) == type(of:rhs)`?

Zhao Xin

On Tue, Jul 4, 2017 at 8:00 AM, David Baraff via swift-users <
swift-users@swift.org> wrote:

> I’m searching for the simplest way to write a function
> func maybeEqual(_ lhs:T, _rhs:T) -> Bool
>
> where it returns lhs == rhs if T is equatable, and false, otherwise.
> I tried
>
> func maybeEqual(_ lhs:T, _rhs:T) -> Bool {
> return false
> }
>
> func maybeEqual(_ lhs:T, _ rhs:T) -> Bool {
> return lhs == rhs
> }
>
> but that doesn’t work.  Is there a way to express a type not matching
> something?
> Alternately, how can I write this?
>
>
> ___
> 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] Covariance in Generic Protocols & Proposal 0142

2017-06-25 Thread Zhao Xin via swift-users
`protocol A: GenericProtocol where Instance == String { }` means, A is
something that `Instance` must be `String`.
However, it doesn't mean `Instance` has already been `String`.

So without assigning your `Instance`, the compiler doesn't know the type of
your `Instance`.

Zhao Xin

On Mon, Jun 26, 2017 at 11:46 AM, Justin Jia via swift-users <
swift-users@swift.org> wrote:

> Hi,
>
> I’m trying to implement something like this using Swift 4 after proposal
> 0142 is implemented:
>
> ```
> protocol GenericProtocol {
> associatedtype Instance
> func foo() -> Instance
> func bar() -> Instance
> // and more...
> }
>
> protocol A: GenericProtocol where Instance == String { }
> protocol B: GenericProtocol where Instance == Int { }
> protocol C: GenericProtocol where Instance == Double { }
> // and more…
>
> class Bar {
> var a: A // Error: Protocol ‘A' can only be used as a generic
> constraint because it has Self or associated type requirements
> var b: B // Error: Protocol ‘B' can only be used as a generic
> constraint because it has Self or associated type requirements
> var c: C // Error: Protocol ‘C' can only be used as a generic
> constraint because it has Self or associated type requirements
> // and more...
> }
> ```
>
> However, I’m still getting the `Protocol ‘A' can only be used as a generic
> constraint because it has Self or associated type requirements` error.
>
> Instead, the only thing I can do right now is to duplicate my code:
>
> (Just in case your are wondering, I need this syntax to simplify some code
> I’m working on https://github.com/TintPoint/Overlay/tree/swift-4.0)
>
> ```
> protocol A {
> func foo() -> String
> func bar() -> String
> // and more...
> }
>
> protocol B {
> func foo() -> Int
> func bar() -> Int
> // and more...
> }
>
> protocol B {
> func foo() -> Double
> func bar() -> Double
> // and more...
> }
>
> // and more...
>
> class Bar {
> var a: A // OK
> var b: B // OK
> var c: C // OK
> // and more...
> }
> ```
>
> Am I doing something wrong here? Is it Swift’s current limitation that can
> be improved in a future version of Swift? Or it needs a special syntax and
> a separate proposal?
>
> Thank you in advance for your help!
>
> Sincerely,
> Justin
>
> ___
> 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 binding with non-optional expression

2017-06-04 Thread Zhao Xin via swift-users
Then I knew it.

if let a: A = A() { // this is a warning as it treats like always true

print("something") // this line always runs

}

For

if let a = A() { // show an error as the compiler thinks you are missing
something.

}

For me, the first example, explicitly given the type of `a`, so it is a
warning. The second example, is one step farther than the first one. And it
is shown as an error.

Each one of them is correct by itself. But putting together, there is a
self-contradictory feeling.


Zhao Xin


On Sun, Jun 4, 2017 at 6:00 PM, Martin R  wrote:

> I don’t think that explains it (or perhaps I did not understand your
> response correctly).
>
> Here is the same issue with a custom type (which does not have a failable
> initializer):
>
>struct A { }
>
>if let a = A() { }
>// error: initializer for conditional binding must have Optional type,
> not 'A'
>
>if let a: A = A() { }
>// warning: non-optional expression of type 'A' used in a check for
> optionals
>
>
> > Am 02.06.2017 um 15:49 schrieb Zhao Xin :
> >
> > I think it did an unnecessary implicitly casting. For example,
> >
> > let y = Int(exactly: 5)
> > print(type(of:y)) // Optional
> >
> > You code equals to
> >
> > if let y:Int = Int(exactly: 5) { }
> >
> > However, I don't know why it did that. Maybe because of type inferring?
> >
> > Zhaoxin
> >
> > On Fri, Jun 2, 2017 at 8:40 PM, Martin R via swift-users <
> swift-users@swift.org> wrote:
> > This following code fails to compile (which is correct, as far as I can
> judge that):
> >
> >if let x = 5 { }
> >// error: initializer for conditional binding must have Optional
> type, not 'Int'
> >
> > But why is does it compile (with a warning) if an explicit type
> annotation is added?
> >
> >if let y: Int = 5 { }
> >// warning: non-optional expression of type 'Int' used in a check for
> optionals
> >
> > Tested with Xcode 8.3.2 and both the build-in Swift 3.1 toolchain and
> the Swift 4.0 snapshot from May 25, 2017.
> >
> > I am just curious and would like to understand if there is fundamental
> difference between those statements.
> >
> > Regards, Martin
> >
> >
> >
> > ___
> > 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] Calling default implementation of protocol methods as selectors

2017-06-04 Thread Zhao Xin via swift-users
Will this work?

class TapGestureRecognizer: UITapGestureRecognizer {

var onTap: (() -> Void)?

init(onTap: (() -> Void)?) {

self.onTap = onTap

super.init(target: nil, action: nil)

*self.removeTarget(nil, action: nil)*

self.addTarget(self, action: #selector(internalTapHandler))

print(self)

}



@objc private func internalTapHandler() {

onTap?()

}

}

Zhao Xin

On Sun, Jun 4, 2017 at 5:24 PM, Nate Birkholz  wrote:

> Also, note that I tried the following:
>
> class BlockTapGestureRecognizer: UIGestureRecognizer {
> var onTap: (() -> Void)?
> init(onTap: (() -> Void)?) {
> self.onTap = onTap
> super.init(target: nil, action: nil)
> self.addTarget(self, action: #selector(internalTapHandler))
> print(self)
> }
>
> @objc private func internalTapHandler() {
> onTap?()
> }
> }
>
> And the object prints looking okay:
>
>  UIGestureRecognizer; state = Possible; view = ; target=
> <(action=internalTapHandler, target= 0x1701998b0>)>>
>
> But it doesn't in practice work. The documentation for the (target:
> action:) initializer states:
>
> target: An object that is the recipient of action messages sent by the
> receiver when it recognizes a gesture. nil is not a valid value.
> action: A selector that identifies the method implemented by the target to
> handle the gesture recognized by the receiver. The action selector must
> conform to the signature described in the class overview. NULL is not a
> valid value.
>
> So something is going on inside there when the nil values are passed to
> the recognizer. As the documentation states, nil is not a valid value and
> it must cause troubles.
>
> Or I did something wrong?
>
>
>
> On Sun, Jun 4, 2017 at 1:55 AM, Nate Birkholz  wrote:
>
>> Ah, I didn't read the rest of the thread. As Zhao Xin notes, you cannot
>> call super.init(target: self, action: #selector()), and you cannot call
>> super.init() in a subclass init or convenience init, it *has* to be the
>> designated init method init(target:action:). That's too bad, closure-based
>> gesture recognizers would be snazzy and swifty and I'd love to see them as
>> part of UIKit.
>>
>> I could write my own custom implementations of subclassed
>> UIKit.UIGestureRecognizerSubclass(es), but as the screens in question
>> have tap, swipe up, swipe down, and swipe right gesture recognizers, I feel
>> its overkill to write all that to avoid repeating ~10 lines of code.
>>
>> On Sun, Jun 4, 2017 at 1:21 AM, Nate Birkholz 
>> wrote:
>>
>>> I briefly considered something like this but didn't explore it. Elegant.
>>>
>>> Sent from my iPhone, please excuse brevity and errors
>>>
>>> On Jun 3, 2017, at 9:38 PM, Geordie Jay  wrote:
>>>
>>> I am dealing with a variant of this on Android right now. I have just
>>> subclassed e.g. UITapGestureRecognizer to perform the 2nd variant above and
>>> externally accept a closure as its argument. I'm writing this on my phone
>>> so forgive any syntax errors or accidental omissions:
>>>
>>> class TapGestureRecognizer: UITapGestureRecognizer {
>>> var onTap: (() -> Void)?
>>> init(onTap: (() -> Void)?) {
>>> self.onTap = onTap
>>> super.init(target: self, action: #selector(internalTapHandler))
>>> }
>>>
>>> @objc private func internalTapHandler() {
>>> onTap?()
>>> }
>>> }
>>>
>>> class Baz: Foo {
>>> init() {
>>> let tapRecognizer = TapGestureRecognizer(onTap: self.bar)
>>> }
>>> }
>>>
>>>
>>> Cheers,
>>> Geordie
>>> On Sat 3. Jun 2017 at 16:53, Nate Birkholz via swift-users <
>>> swift-users@swift.org> wrote:
>>>
 Thanks, the second had occurred to me, but felt a little too much like
 in practice it would make the code harder to understand.

 On Fri, Jun 2, 2017 at 9:58 PM, Zhao Xin  wrote:

> I found two workarounds.
>
> 1.
>
> protocol Foo: class {
>
> func bar()
>
> }
>
>
> class Base:Foo {
>
> @objc func bar() {
>
> print("bar")
>
> }
>
> }
>
>
> class Baz: Base {
>
> override init() {
>
> super.init()
>
> let tapRecognizer = UITapGestureRecognizer(target: self,
> action: #selector(bar))
>
> }
>
> }
>
> 2.
>
> protocol Foo: class {
>
> func bar()
>
> }
>
>
> extension Foo {
>
> func bar() {
>
> print("bar")
>
> }
>
> }
>
>
> class Baz: Foo {
>
> init() {
>
> let tapRecognizer = UITapGestureRecognizer(target: self,
> action: #selector(delegate))
>
> }
>
>
>
> @objc func delegate() {
>
> bar()
>
> }
>
> }
>
>
> Zhao Xin
>
>
>
>
>
>

Re: [swift-users] Calling default implementation of protocol methods as selectors

2017-06-03 Thread Zhao Xin via swift-users
I was not talking about the formatting. I am talking about the
implementation.

You can't use `self` before you call `super.init` as you did now. If
 changing your implementation to called `super.init` and then call `self`
in `super.init` again. You would have called `super.init` twice. I don't
know what that means. But it smells bad.

Zhaoxin

On Sun, Jun 4, 2017 at 12:51 PM, Geordie Jay  wrote:

> Thanks for the amendment, and sorry for the (lack of) formatting. I
> painstakingly typed that on my phone with manually-spaced indenting, which
> the Inbox app unhelpfully removed entirely when I pressed send. Pasting
> into Xcode should do the trick though..
>
> Geordie
>
> On Sun 4. Jun 2017 at 14:49, Zhao Xin  wrote:
>
>> You should change to another way. Using `self` in `super.init` is not
>> allowed.
>>
>> Zhaoxin
>>
>> On Sun, Jun 4, 2017 at 12:38 PM, Geordie Jay  wrote:
>>
>>> I am dealing with a variant of this on Android right now. I have just
>>> subclassed e.g. UITapGestureRecognizer to perform the 2nd variant above and
>>> externally accept a closure as its argument. I'm writing this on my phone
>>> so forgive any syntax errors or accidental omissions:
>>>
>>> class TapGestureRecognizer: UITapGestureRecognizer {
>>> var onTap: (() -> Void)?
>>> init(onTap: (() -> Void)?) {
>>> self.onTap = onTap
>>> super.init(target: self, action: #selector(internalTapHandler))
>>> }
>>>
>>> @objc private func internalTapHandler() {
>>> onTap?()
>>> }
>>> }
>>>
>>> class Baz: Foo {
>>> init() {
>>> let tapRecognizer = TapGestureRecognizer(onTap: self.bar)
>>> }
>>> }
>>>
>>>
>>> Cheers,
>>> Geordie
>>>
>>> On Sat 3. Jun 2017 at 16:53, Nate Birkholz via swift-users <
>>> swift-users@swift.org> wrote:
>>>
 Thanks, the second had occurred to me, but felt a little too much like
 in practice it would make the code harder to understand.

 On Fri, Jun 2, 2017 at 9:58 PM, Zhao Xin  wrote:

> I found two workarounds.
>
> 1.
>
> protocol Foo: class {
>
> func bar()
>
> }
>
>
> class Base:Foo {
>
> @objc func bar() {
>
> print("bar")
>
> }
>
> }
>
>
> class Baz: Base {
>
> override init() {
>
> super.init()
>
> let tapRecognizer = UITapGestureRecognizer(target: self,
> action: #selector(bar))
>
> }
>
> }
>
> 2.
>
> protocol Foo: class {
>
> func bar()
>
> }
>
>
> extension Foo {
>
> func bar() {
>
> print("bar")
>
> }
>
> }
>
>
> class Baz: Foo {
>
> init() {
>
> let tapRecognizer = UITapGestureRecognizer(target: self,
> action: #selector(delegate))
>
> }
>
>
>
> @objc func delegate() {
>
> bar()
>
> }
>
> }
>
>
> Zhao Xin
>
>
>
>
>
>
> On Sat, Jun 3, 2017 at 10:35 AM, Nate Birkholz via swift-users <
> swift-users@swift.org> wrote:
>
>> protocol Foo: class {
>> func bar()
>> }
>>
>> extension Foo {
>> func bar() {
>>  print("bar")
>> }
>> }
>>
>> class Baz: Foo {
>> init() {
>> let tapRecognizer = UITapGestureRecognizer(target: self,
>> action: #selector(bar))
>> }
>> }
>>
>> the #selector tells me: "Argument of '#selector' refers to instance
>> method 'bar()' that is not exposed to Objective-C" and asks me to add 
>> @objc
>> to the method definition.
>>
>> Adding @objc to the method tells me: "@objc can only be used with
>> members of classes, @objc protocols, and concrete extensions of classes"
>>
>> Adding @objc to the protocol doesn't fix it, just introduces new
>> issues.
>>
>> "dynamic" cannot be applied to a protocol, so cannot be used
>> alternatively.
>>
>> Is there a way to get around this? If a method is called by a gesture
>> recognizer, is there no way to have a default protocol implementation? 
>> I'd
>> like to use default implementations if possible to make my code more DRY.
>>
>> Is there a roadmap/plan for swift-native selector dispatch?
>>
>> Thanks. I look forward to the inevitable reply revealing the dumb
>> thing I missed. :)
>>
>> --
>> Nate Birkholz
>>
>> ___
>> swift-users mailing list
>> swift-users@swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
>>
>>
>


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

>>>
>>

Re: [swift-users] Calling default implementation of protocol methods as selectors

2017-06-03 Thread Zhao Xin via swift-users
You should change to another way. Using `self` in `super.init` is not
allowed.

Zhaoxin

On Sun, Jun 4, 2017 at 12:38 PM, Geordie Jay  wrote:

> I am dealing with a variant of this on Android right now. I have just
> subclassed e.g. UITapGestureRecognizer to perform the 2nd variant above and
> externally accept a closure as its argument. I'm writing this on my phone
> so forgive any syntax errors or accidental omissions:
>
> class TapGestureRecognizer: UITapGestureRecognizer {
> var onTap: (() -> Void)?
> init(onTap: (() -> Void)?) {
> self.onTap = onTap
> super.init(target: self, action: #selector(internalTapHandler))
> }
>
> @objc private func internalTapHandler() {
> onTap?()
> }
> }
>
> class Baz: Foo {
> init() {
> let tapRecognizer = TapGestureRecognizer(onTap: self.bar)
> }
> }
>
>
> Cheers,
> Geordie
>
> On Sat 3. Jun 2017 at 16:53, Nate Birkholz via swift-users <
> swift-users@swift.org> wrote:
>
>> Thanks, the second had occurred to me, but felt a little too much like in
>> practice it would make the code harder to understand.
>>
>> On Fri, Jun 2, 2017 at 9:58 PM, Zhao Xin  wrote:
>>
>>> I found two workarounds.
>>>
>>> 1.
>>>
>>> protocol Foo: class {
>>>
>>> func bar()
>>>
>>> }
>>>
>>>
>>> class Base:Foo {
>>>
>>> @objc func bar() {
>>>
>>> print("bar")
>>>
>>> }
>>>
>>> }
>>>
>>>
>>> class Baz: Base {
>>>
>>> override init() {
>>>
>>> super.init()
>>>
>>> let tapRecognizer = UITapGestureRecognizer(target: self,
>>> action: #selector(bar))
>>>
>>> }
>>>
>>> }
>>>
>>> 2.
>>>
>>> protocol Foo: class {
>>>
>>> func bar()
>>>
>>> }
>>>
>>>
>>> extension Foo {
>>>
>>> func bar() {
>>>
>>> print("bar")
>>>
>>> }
>>>
>>> }
>>>
>>>
>>> class Baz: Foo {
>>>
>>> init() {
>>>
>>> let tapRecognizer = UITapGestureRecognizer(target: self,
>>> action: #selector(delegate))
>>>
>>> }
>>>
>>>
>>>
>>> @objc func delegate() {
>>>
>>> bar()
>>>
>>> }
>>>
>>> }
>>>
>>>
>>> Zhao Xin
>>>
>>>
>>>
>>>
>>>
>>>
>>> On Sat, Jun 3, 2017 at 10:35 AM, Nate Birkholz via swift-users <
>>> swift-users@swift.org> wrote:
>>>
 protocol Foo: class {
 func bar()
 }

 extension Foo {
 func bar() {
  print("bar")
 }
 }

 class Baz: Foo {
 init() {
 let tapRecognizer = UITapGestureRecognizer(target: self,
 action: #selector(bar))
 }
 }

 the #selector tells me: "Argument of '#selector' refers to instance
 method 'bar()' that is not exposed to Objective-C" and asks me to add @objc
 to the method definition.

 Adding @objc to the method tells me: "@objc can only be used with
 members of classes, @objc protocols, and concrete extensions of classes"

 Adding @objc to the protocol doesn't fix it, just introduces new issues.

 "dynamic" cannot be applied to a protocol, so cannot be used
 alternatively.

 Is there a way to get around this? If a method is called by a gesture
 recognizer, is there no way to have a default protocol implementation? I'd
 like to use default implementations if possible to make my code more DRY.

 Is there a roadmap/plan for swift-native selector dispatch?

 Thanks. I look forward to the inevitable reply revealing the dumb thing
 I missed. :)

 --
 Nate Birkholz

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


>>>
>>
>>
>> --
>> 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] Calling default implementation of protocol methods as selectors

2017-06-02 Thread Zhao Xin via swift-users
I found two workarounds.

1.

protocol Foo: class {

func bar()

}


class Base:Foo {

@objc func bar() {

print("bar")

}

}


class Baz: Base {

override init() {

super.init()

let tapRecognizer = UITapGestureRecognizer(target: self, action:
#selector(bar))

}

}

2.

protocol Foo: class {

func bar()

}


extension Foo {

func bar() {

print("bar")

}

}


class Baz: Foo {

init() {

let tapRecognizer = UITapGestureRecognizer(target: self, action:
#selector(delegate))

}



@objc func delegate() {

bar()

}

}


Zhao Xin






On Sat, Jun 3, 2017 at 10:35 AM, Nate Birkholz via swift-users <
swift-users@swift.org> wrote:

> protocol Foo: class {
> func bar()
> }
>
> extension Foo {
> func bar() {
>  print("bar")
> }
> }
>
> class Baz: Foo {
> init() {
> let tapRecognizer = UITapGestureRecognizer(target: self, action:
> #selector(bar))
> }
> }
>
> the #selector tells me: "Argument of '#selector' refers to instance method
> 'bar()' that is not exposed to Objective-C" and asks me to add @objc to the
> method definition.
>
> Adding @objc to the method tells me: "@objc can only be used with members
> of classes, @objc protocols, and concrete extensions of classes"
>
> Adding @objc to the protocol doesn't fix it, just introduces new issues.
>
> "dynamic" cannot be applied to a protocol, so cannot be used
> alternatively.
>
> Is there a way to get around this? If a method is called by a gesture
> recognizer, is there no way to have a default protocol implementation? I'd
> like to use default implementations if possible to make my code more DRY.
>
> Is there a roadmap/plan for swift-native selector dispatch?
>
> Thanks. I look forward to the inevitable reply revealing the dumb thing I
> missed. :)
>
> --
> 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] Optional binding with non-optional expression

2017-06-02 Thread Zhao Xin via swift-users
I think it did an unnecessary implicitly casting. For example,

let y = Int(exactly: 5)

print(type(of:y)) // Optional


You code equals to


if let y:Int = Int(exactly: 5) { }


However, I don't know why it did that. Maybe because of type inferring?

Zhaoxin

On Fri, Jun 2, 2017 at 8:40 PM, Martin R via swift-users <
swift-users@swift.org> wrote:

> This following code fails to compile (which is correct, as far as I can
> judge that):
>
>if let x = 5 { }
>// error: initializer for conditional binding must have Optional type,
> not 'Int'
>
> But why is does it compile (with a warning) if an explicit type annotation
> is added?
>
>if let y: Int = 5 { }
>// warning: non-optional expression of type 'Int' used in a check for
> optionals
>
> Tested with Xcode 8.3.2 and both the build-in Swift 3.1 toolchain and the
> Swift 4.0 snapshot from May 25, 2017.
>
> I am just curious and would like to understand if there is fundamental
> difference between those statements.
>
> Regards, Martin
>
>
>
> ___
> 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] Conforming to the protocol requirements with implicitly unwrapped optional

2017-05-29 Thread Zhao Xin via swift-users
You can try this.

protocol Container : class {

var component: Component { get }

}


class ConcreteContainer : Container {

lazy var component: Component = { return Component(container: self) }()

}


class Component {

unowned let container: Container

init(container: Container) {

self.container = container

}

}


Zhaoxin

On Mon, May 29, 2017 at 11:48 PM, Anton Bronnikov 
wrote:

> Like I mentioned, it is necessary to use optional, but it can not be nil.
> Consider the following example where I have to use an optional in order to
> break retention cycle:
>
> protocol Container : class {
> var component: Component { get }
> }
>
> class ConcreteContainer : Container {
> var component: Component! = nil
> init() {
> component = Component(container: self)
> }
> }
>
> class Component {
> unowned let container: Container
> init(container: Container) {
> self.container = container
> }
> }
>
> *Playground execution failed: error: scratchpad.playground:5:7: error:
> type 'ConcreteContainer' does not conform to protocol 'Container'*
> *class ConcreteContainer : Container {*
> *  ^*
>
> *scratchpad.playground:2:9: note: protocol requires property 'component'
> with type 'Component'; do you want to add a stub?*
> *var component: Component { get }*
> *^*
>
> *scratchpad.playground:6:9: note: candidate has non-matching type
> 'Component!'*
> *var component: Component! = nil*
> *^*
>
>
> Cheers,
> Anton
>
> P.S. Declaring protocol as
>
> protocol Container : class {
> var component: Component! { get }
> }
>
>
> .. would also work of course, but my question is not about how to move
> forward, rather about whether such setup is deliberate.
>
>
> On 29 May 2017, at 08:20, Zhao Xin  wrote:
>
> Why you have to use `unwrapped optional` at the first place? If you have
> to use it, it means it could be nil. So it won't conform the protocol,
> which requires the `value` never nil.
>
> Zhaoxin
>
> On Mon, May 29, 2017 at 12:37 PM, Anton Bronnikov via swift-users <
> swift-users@swift.org> wrote:
>
>> Hi All,
>>
>> If I have a protocol with a property requirement such as:
>>
>> protocol Foo {
>> var value: Int { get }
>> }
>>
>>
>> .. and I need to conform to it using an implicitly unwrapped optional
>> like:
>>
>> struct Bar : Foo {
>> let value: Int! = nil
>> }
>>
>>
>> .. then the compiler fails with an error:
>>
>> *Playground execution failed: error: scratchpad.playground:5:8: error:
>> type 'Bar' does not conform to protocol 'Foo'*
>> *struct Bar : Foo {*
>> *   ^*
>>
>> *scratchpad.playground:2:9: note: protocol requires property 'value' with
>> type 'Int'; do you want to add a stub?*
>> *var value: Int { get }*
>> *^*
>>
>> *scratchpad.playground:6:9: note: candidate has non-matching type 'Int!'*
>> *let value: Int! = nil*
>> *^*
>>
>> Technically, I understand why the error, and currently work around it
>> with a cumbersome:
>>
>> struct Bar : Foo {
>> var value: Int { return _value! }
>> let _value: Int? = nil
>> }
>>
>>
>> However, I keep wondering - would it not be making sense to accept
>> implicitly unwrapped optionals as a conformance to be base-type
>> requirements?  It sort of works just like that in all other parts of the
>> language.
>>
>> Or in other words, is this by design, or should I probably create an
>> issue for this?
>>
>> Thank you.
>> Cheers,
>> Anton
>>
>> P.S. The example is oversimplified for the sake of clarity, in practice
>> the property just has to be an optional - implicitly unwrapped or not -
>> because it’s a part of the composite that holds unowning reference to its
>> container object.
>>
>>
>> ___
>> 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] Conforming to the protocol requirements with implicitly unwrapped optional

2017-05-29 Thread Zhao Xin via swift-users
Why you have to use `unwrapped optional` at the first place? If you have to
use it, it means it could be nil. So it won't conform the protocol, which
requires the `value` never nil.

Zhaoxin

On Mon, May 29, 2017 at 12:37 PM, Anton Bronnikov via swift-users <
swift-users@swift.org> wrote:

> Hi All,
>
> If I have a protocol with a property requirement such as:
>
> protocol Foo {
> var value: Int { get }
> }
>
>
> .. and I need to conform to it using an implicitly unwrapped optional like:
>
> struct Bar : Foo {
> let value: Int! = nil
> }
>
>
> .. then the compiler fails with an error:
>
> *Playground execution failed: error: scratchpad.playground:5:8: error:
> type 'Bar' does not conform to protocol 'Foo'*
> *struct Bar : Foo {*
> *   ^*
>
> *scratchpad.playground:2:9: note: protocol requires property 'value' with
> type 'Int'; do you want to add a stub?*
> *var value: Int { get }*
> *^*
>
> *scratchpad.playground:6:9: note: candidate has non-matching type 'Int!'*
> *let value: Int! = nil*
> *^*
>
> Technically, I understand why the error, and currently work around it with
> a cumbersome:
>
> struct Bar : Foo {
> var value: Int { return _value! }
> let _value: Int? = nil
> }
>
>
> However, I keep wondering - would it not be making sense to accept
> implicitly unwrapped optionals as a conformance to be base-type
> requirements?  It sort of works just like that in all other parts of the
> language.
>
> Or in other words, is this by design, or should I probably create an issue
> for this?
>
> Thank you.
> Cheers,
> Anton
>
> P.S. The example is oversimplified for the sake of clarity, in practice
> the property just has to be an optional - implicitly unwrapped or not -
> because it’s a part of the composite that holds unowning reference to its
> container object.
>
>
> ___
> 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] Why inout protocol parameter in function work with strange

2017-05-27 Thread Zhao Xin via swift-users
Because generic uses `Car` instead of `Position` when running the code, so
there is no casting as `car as Position` as in your original code. The
`T:Position`
part restricts that the type conforms `Position`, but it won't use `Position`,
it uses the type.

Zhaoxin

On Sat, May 27, 2017 at 4:58 PM, Седых Александр via swift-users <
swift-users@swift.org> wrote:

> Thanks. Why generic function don not require memory allocate for inout
> variable, even if it is protocol type?
>
>
> Пятница, 26 мая 2017, 19:35 +03:00 от Guillaume Lessard <
> gless...@tffenterprises.com>:
>
> In your example, the compiler needs a parameter of type Position. Car is a
> type of Position, but they are not interchangeable. See below:
>
> > On May 26, 2017, at 00:33, Седых Александр via swift-users <
> swift-users@swift.org> wrote:
> >
> > protocol Position {
> > var x: Double { getset }
> > }
> >
> > struct Car: Position {
> > var x: Double
> > }
> >
> > func move(item: inout Position) {
> > item.x += 1
> > }
> >
> > var car = Car(x: 50)
>
> var pos: Position = car
>
> move(item: ) // this works.
> assert(pos.x == 51) // works
>
> The move function as you wrote it requires the memory representation of a
> Position variable, which Car does not have; when you assign it to a
> Position variable, the Car struct gets accessed through an indirection
> layer. (There was a WWDC talk about this last year or the year before.)
>
> You may want a generic function instead:
>
> func move(item: inout P) {
>   item.x += 1
> }
>
> move(item: ) // this works, since it’s now calling the generic
> function.
> assert(car.x == 51) // works
>
> 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] NSDictionary passed through Swift loses access to category methods

2017-05-23 Thread Zhao Xin via swift-users
I don't think this is the good place for your question. Maybe stackoverflow
or apple developer forum is more suitable.

Did you added the header filename of the category to your bridge file?
Also, is there the method name in the header file as well? You know,
sometimes people wouldn't include the method name in the header but
implementing it directly in the .m file.

Zhaoxin

On Wed, May 24, 2017 at 4:10 AM, Russell Finn via swift-users <
swift-users@swift.org> wrote:

> I'm having an issue with an NSDictionary that is passing through Swift
> code and back to Objective-C losing access to a method implemented by a
> category on NSDictionary. There is clearly some subtlety about bridged
> dictionaries that I'm missing, and I'd appreciate any clarification that
> the list can provide.
>
>
> Specifically: I have a Swift 3 application that uses some legacy
> Objective-C classes.  One of these classes relies on a category on
> NSDictionary that implements a method called `-boolValueForKey:`.
>
>
> In the main application, the Swift code calls a method on a remote object
> proxy that returns an NSDictionary, which get bridged back to a Swift
> dictionary (`[AnyHashable: Any]`).  This bridged dictionary is passed to a
> method on the legacy Objective-C class that calls the `-boolValueForKey:`
> method from the category.  At this point, a runtime exception occurs that
> says the dictionary object (which at this point is a
> `_SwiftDeferredNSDictionary`, according to the debugger) doesn’t recognize
> the selector `-boolValueForKey:`.
>
>
> I can work around the issue in my code by modifying the legacy Objective-C
> class and inlining the implementation of `-boolValueForKey:` — but is there
> a better general approach?
>
> Thanks — Russell
>
>
> ___
> 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 localisation, percentage sign escaping

2017-05-11 Thread Zhao Xin via swift-users
Forgot to show an example.

In Swift, below code won't work,

let says = NSLocalizedString("It runs \(count) times", comment: "run times")

You should use

let says = String.localizedStringWithFormat(NSLocalizedString("It runs %@
times", comment: "run times"), String(count))

Zhaoxin

On Fri, May 12, 2017 at 2:23 AM, rintaro ishizaki via swift-users <
swift-users@swift.org> wrote:

>
>
> 2017-05-11 18:44 GMT+09:00 Adam Sutcliffe via swift-users <
> swift-users@swift.org>:
>
>> Hi,
>>
>> I've been having an issue with a localised string,, one of which has a
>> percentage sign in it:
>>
>> "GAMERANK_5_DESC" = "Wow! You're racing ahead. Only 5%% of our users get
>> here!";
>>
>> the key is built as such:
>>
>> Obj-c : NSString *key = [NSString stringWithFormat:@"GAMERANK_%@_DESC"
>> ,rank];
>>
>> Swift: let key = "GAMERANK_\(rank)_DESC"
>>
>> Then localised with the same macro:  NSLocalizedString(key, @"");
>>
>> The output is different though:
>>
>> Obj- C = "Wow! You're racing ahead. Only 5% of our users get here!"
>> Swift = "Wow! You're racing ahead. Only 5%% of our users get here!"
>>
>
> How do you check the output?
> If you are using NSLog(output) in Obj-C and print(output) in Swift, that
> is why.
> The first parameter of NSLog is a format.
>
>
>>
>> Is this a bug in the swifts localisation parsing? Does the percentage
>> sign not need to be escaped in Swift?
>>
>> Cheers
>>
>> --
>>
>> –
>> ADAM SUTCLIFFE
>> Software Engineer
>>
>> –
>> +44 (0)7786 692 639
>> a...@peak.net 
>> peak.net
>>
>> ___
>> 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] Why is static a keyword?

2017-05-11 Thread Zhao Xin via swift-users
Yes, I had. There was a `class` and `static` post under it. But I disagreed
that and  my interpretation was just opposite.

Zhaoxin

On Fri, May 12, 2017 at 1:11 AM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> Have you read closely the bug issue before posting your answer?
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 11. Mai 2017 um 19:05:13, Zhao Xin (owe...@gmail.com) schrieb:
>
> No. I think it is just a compromise.
>
> Zhaoxin
>
> On Fri, May 12, 2017 at 1:01 AM, Adrian Zubarev <
> adrian.zuba...@devandartist.com> wrote:
>
>> I don’t think this is the answer that was asked for. I bet it’s more a
>> technical question from the internal point of of view.
>>
>>
>> --
>> Adrian Zubarev
>> Sent with Airmail
>>
>> Am 11. Mai 2017 um 18:59:58, Zhao Xin via swift-users (
>> swift-users@swift.org) schrieb:
>>
>> In Swift, you use `static in struct and enum` and `class in class`. For
>> example,
>>
>> struct Foo {
>>
>> static func bar() {
>>
>>
>>
>> }
>>
>> }
>>
>>
>> class ClassFoo {
>>
>> class func bar() {
>>
>>
>>
>> }
>>
>> }
>>
>>
>> Another the `class func bar()` can replace to `static` as well. Here the
>> `static` and `class` are equal in functions of classes.
>>
>>
>> And `class` is a keyword.
>>
>>
>> class ClassFoo2 {
>>
>> static func bar() {
>>
>>
>>
>> }
>>
>> }
>>
>>
>> Zhaoxin
>>
>>
>>
>> On Fri, May 12, 2017 at 12:17 AM, Jose Cheyo Jimenez via swift-users <
>> swift-users@swift.org> wrote:
>>
>>> I was expecting static to be a builtin. Does anybody know why it must be
>>> a keyword?
>>>
>>> Background. https://bugs.swift.org/browse/SR-4834
>>>
>>> ___
>>> 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] Why is static a keyword?

2017-05-11 Thread Zhao Xin via swift-users
No. I think it is just a compromise.

Zhaoxin

On Fri, May 12, 2017 at 1:01 AM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> I don’t think this is the answer that was asked for. I bet it’s more a
> technical question from the internal point of of view.
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 11. Mai 2017 um 18:59:58, Zhao Xin via swift-users (
> swift-users@swift.org) schrieb:
>
> In Swift, you use `static in struct and enum` and `class in class`. For
> example,
>
> struct Foo {
>
> static func bar() {
>
>
>
> }
>
> }
>
>
> class ClassFoo {
>
> class func bar() {
>
>
>
> }
>
> }
>
>
> Another the `class func bar()` can replace to `static` as well. Here the
> `static` and `class` are equal in functions of classes.
>
>
> And `class` is a keyword.
>
>
> class ClassFoo2 {
>
> static func bar() {
>
>
>
> }
>
> }
>
>
> Zhaoxin
>
>
>
> On Fri, May 12, 2017 at 12:17 AM, Jose Cheyo Jimenez via swift-users <
> swift-users@swift.org> wrote:
>
>> I was expecting static to be a builtin. Does anybody know why it must be
>> a keyword?
>>
>> Background. https://bugs.swift.org/browse/SR-4834
>>
>> ___
>> 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] Why is static a keyword?

2017-05-11 Thread Zhao Xin via swift-users
In Swift, you use `static in struct and enum` and `class in class`. For
example,

struct Foo {

static func bar() {



}

}


class ClassFoo {

class func bar() {



}

}


Another the `class func bar()` can replace to `static` as well. Here the
`static` and `class` are equal in functions of classes.


And `class` is a keyword.


class ClassFoo2 {

static func bar() {



}

}


Zhaoxin



On Fri, May 12, 2017 at 12:17 AM, Jose Cheyo Jimenez via swift-users <
swift-users@swift.org> wrote:

> I was expecting static to be a builtin. Does anybody know why it must be a
> keyword?
>
> Background. https://bugs.swift.org/browse/SR-4834
>
> ___
> 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] Help! Slicing an array is very expensive

2017-05-08 Thread Zhao Xin via swift-users
Have you try other approaches? Maybe just write your data to cache on disk
and read it back will be quicker?

Zhaoxin

On Tue, May 9, 2017 at 8:01 AM, Philippe Hausler via swift-users <
swift-users@swift.org> wrote:

> I wonder if Data might be a better tool for the job here since it is it’s
> own slice type and would avoid copying large amounts of data into temporary
> buffers.
>
> > On May 8, 2017, at 16:47, Rick Mann via swift-users <
> swift-users@swift.org> wrote:
> >
> > I have this C library that interacts with some hardware over the network
> that produces a ton of data. It tells me up front the maximum size the data
> might be so I can allocate a buffer for it, then does a bunch of network
> requests downloading that data into the buffer, then tells me when it's
> done and what the final, smaller size is.
> >
> > Thanks to previous discussions on the list, I settled on using a [UInt8]
> as the buffer, because it let me avoid various .withUnsafePointer{} calls
> (I need the unsafe buffer pointer to live outside the scope of the
> closures). Unfortunately, When I go to shrink the buffer to its final size
> with:
> >
> >self.dataBuffer = Array(self.dataBuffer![0 ..< finalBufferSize])
> >
> > This ends up taking over 2 minutes to complete (on an iPad Pro).
> finalBufferSize is very large, 240 MB, but I think it's doing a very naive
> copy.
> >
> > I've since worked around this problem, but is there any way to improve
> on this?
> >
> > 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


Re: [swift-users] optional variable with ternary operator

2017-05-08 Thread Zhao Xin via swift-users
I wonder if it has ever been allowed? I am using Xcode and it never allows
that.
For you specific question, you can use

var number:Int?

let result = (number ?? -1) > 0 ? 1 : 2


Zhaoxin

On Tue, May 9, 2017 at 1:39 AM, Erica Sadun via swift-users <
swift-users@swift.org> wrote:

> I believe this falls under "future directions" for comparison reform.
>
> Here's an example of a short term solution: https://gist.github.com/erica/
> 77b110e17e51dbea7d6934e6582f627f
>
> -- E, who moved this from SE to Swift Users
>
>
> On May 8, 2017, at 10:13 AM, Saagar Jha via swift-evolution <
> swift-evolut...@swift.org> wrote:
>
> Well, you’re not allowed to compare optionals any more. You can try
> binding the value to an Int, so that it’s not an optional anymore:
>
> if let number = number {
> let result = number > 0 ? 1 : 2
> }
>
> Either way, you’ll have to decide what you think should happen when number
> is nil.
>
> Saagar Jha
>
> On May 8, 2017, at 00:36, Suresh Kansujiya via swift-evolution <
> swift-evolut...@swift.org> wrote:
>
> Hey,
>
> i am using ternary operator with optional variable. like below ex.
>
>
>> *var number:Int?**let result = number > 0 ? 1 : 2  *
>
> *here i am getting this waring : comparison operators with optionals were
> removed from the Swift Standard Library. Consider refactoring the code to
> use the non-optional operators*
> Note : i must need to use ternary operator for checking.
>
> Regards
> Suresh Kansujiya
> ___
> swift-evolution mailing list
> swift-evolut...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> ___
> swift-evolution mailing list
> swift-evolut...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
> ___
> 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] Making Error sub-enums Equatable

2017-05-08 Thread Zhao Xin via swift-users
I think you'd better define your own operator, maybe `=~` or something
else. As `==` has already meant something in enum.

Zhaoxin

On Mon, May 8, 2017 at 5:07 PM, Rien via swift-users 
wrote:

> I’d love to know if there is a better way, but a ‘switch’ or 'if case' is
> the only way I know.
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl - A server for websites build in Swift
>
>
>
>
>
>
> > On 08 May 2017, at 11:01, Rick Mann via swift-users <
> swift-users@swift.org> wrote:
> >
> > Seriously, I've been googling this for a half-hour, and I can't find an
> answer (everything that comes up is for ErrorType, absolutely nothing for
> Error).
> >
> > I have an enum:
> >
> > enum MyErrors : Error
> > {
> >case one(String)
> >case two
> >case three(String)
> > }
> >
> > let a: MyErrors = .one("foo")
> > let b = .two
> > let c = .towo
> >
> > I want to compare them with ==, and I don't care about the associated
> types. I can't for the life of me figure out how without an exhaustive
> switch statement in a == definition. Is that the only way?
> >
> > --
> > 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


Re: [swift-users] Flatmap initializer inconsistency

2017-05-01 Thread Zhao Xin via swift-users
That is because for `Optional` the `flatMap` is `func flatMap(_
transform: (Wrapped) throws -> U?) rethrows -> U?` and for `Int`, only
`init?(exactly value: Double)` fits the situation. `init(_ value: Double)`
doesn't return nil. So there is no ambiguity.

Zhaoxin

On Tue, May 2, 2017 at 4:20 AM, Saagar Jha <saa...@saagarjha.com> wrote:

> Well, the question still remains about why the compiler chose
> init(exactly:) over init(). Shouldn’t there at least a warning of ambiguity?
>
> Saagar Jha
>
> On May 1, 2017, at 12:11, Zhao Xin via swift-users <swift-users@swift.org>
> wrote:
>
> In my test, compiler thought you use `init?(exactly value: Double)`, which
> returns nil. So this is not a bug.
>
> Zhaoxin
>
> On Tue, May 2, 2017 at 1:39 AM, Halen Wooten via swift-users <
> swift-users@swift.org> wrote:
>
>> Hi,
>>
>> I'm seeing a weird issue with using an initializer in flatMap. Here's
>> an example:
>>
>> ```
>> let time: TimeInterval? = 662.8258259864
>> let intTimeFlatmap = time.flatMap(Int.init) // nil
>> let intTime = Int(time!) // 662
>> ```
>>
>> I would expect for the flatMap call to return an optional Int with the
>> proper value of 662. Is there something I'm misunderstanding, or is
>> this a swift bug?
>>
>> Thanks,
>> Halen
>> ___
>> 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] Flatmap initializer inconsistency

2017-05-01 Thread Zhao Xin via swift-users
In my test, compiler thought you use `init?(exactly value: Double)`, which
returns nil. So this is not a bug.

Zhaoxin

On Tue, May 2, 2017 at 1:39 AM, Halen Wooten via swift-users <
swift-users@swift.org> wrote:

> Hi,
>
> I'm seeing a weird issue with using an initializer in flatMap. Here's
> an example:
>
> ```
> let time: TimeInterval? = 662.8258259864
> let intTimeFlatmap = time.flatMap(Int.init) // nil
> let intTime = Int(time!) // 662
> ```
>
> I would expect for the flatMap call to return an optional Int with the
> proper value of 662. Is there something I'm misunderstanding, or is
> this a swift bug?
>
> Thanks,
> Halen
> ___
> 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] weak self

2017-05-01 Thread Zhao Xin via swift-users
 [weak self] and [unowned self] are used to solve the problem of Strong
Reference Cycles Between Class Instances

.

If you can grantee self won't be nil during the life time, you should use
`unowned self` instead of `weak self`. If you can't grantee that, you
should use `weak self` and `return self?.myparam ?? 42`. I don't think
using ` if self != nil { return self!.myparam }` is a good idea. The reason
is said by you already.

Zhaoxin





On Mon, May 1, 2017 at 11:42 PM, Dennis Weissmann via swift-users <
swift-users@swift.org> wrote:

>
> On May 1, 2017, at 5:32 PM, Rien  wrote:
>
>
> On 01 May 2017, at 16:59, Dennis Weissmann 
> wrote:
>
>
> On May 1, 2017, at 4:46 PM, Rien via swift-users 
> wrote:
>
> In my code I use a lot of queues. And (very often) I will use [weak self]
> to prevent doing things when ‘self’ is no longer available.
>
> Now I am wondering: how does the compiler know that [weak self] is
> referenced?
>
> I am assuming it keeps a reverse reference from self to the [weak self] in
> order to ‘nil’ the [weak self] when self is nilled.
>
> But when a job is executing it has no control over the exclusive rights to
> [weak self].
>
> I.e. [weak self] may be nilled by an outside event in the middle of say:
>
> if self != nil { return self!.myparam }
>
> The if finding [weak self] non nil, but the return finding [weak self] as
> nil
>
> Is that correct? i.e. should we never use the above if construct but
> always:
>
> return self?.myparam ?? 42
>
>
> Yes, as you said, you never know when self will be nilled out, that's why
> you need to create a (temporary) strong reference to it, work on it, and
> when the block returns, your strong reference is released and self either
> goes away immediately (incase it was released elsewhere after the local
> binding to a strong variable and no other objects had a strong reference to
> it) or it will stay as long as no other object holds a strong reference to
> it.
>
> When the closure is more involved than a view lines, I often do a guard
> let `self` = self else { return } to conveniently work with a strong self
> inside the rest of the closure.
>
>
> I was aware of that practise (use it myself) but I was not sure if it
> would always work.
> I.e. I have not found it documented that
> let strongSelf = self
> will actually retain ‘self’ an not create a strong reference to an
> intermediate reference to self.
>
> It makes sense though, otherwise there would be massive failures ‘out
> there’. ;-)
>
>
> Yes :) local variables (as others too) are strong by default. If you want
> them weak (you should very rarely need that though) you have to explicitly
> mark them weak.
>
> will actually retain ‘self’ an not create a strong reference to an
> intermediate reference to self.
>
>
> Isn't that the same? I might misunderstand you but they would both
> reference the same object, no? So in the end the retain message would be
> sent to the same object, wouldn't it?
>
> Thanks,
> Rien.
>
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl - A server for websites build in Swift
>
>
>
>
>
>
> ___
> swift-users mailing list
> swift-users@swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
> - Dennis
>
>
> - Dennis
>
>
> ___
> 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] odd `==` `!=` behavior with class that inherits `NSObject`

2017-04-19 Thread Zhao Xin via swift-users
 self.name = name
>>
>> }
>>
>>
>>
>> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>>
>> guard type(of:lhs) == type(of:rhs) else { return false }
>>
>> return lhs.name == rhs.name
>>
>> }
>>
>>
>>
>> public static func !=(lhs: Foo, rhs: Foo) -> Bool {
>>
>> guard type(of:lhs) == type(of:rhs) else { return false }
>>
>> return lhs.name != rhs.name
>>
>> }
>>
>> }
>>
>>
>>
>> let a = Foo(name: "bar")
>>
>> let b = Foo(name: "bar")
>>
>>
>>
>> print(a == b) // true, now false
>>
>> print(a != b) // false, now true
>>
>> }
>>
>>
>> Zhaoxin
>>
>> On Wed, Apr 19, 2017 at 11:04 AM, Nate Birkholz <nbirkh...@gmail.com>
>> wrote:
>>
>>> Your issue seems to be that you created a custom implementation for the
>>> `==` operator but not one for the `!=` operator. If I add a custom
>>> implementation for `!=` I get the results you expected. Tthe default
>>> implementation of NSObject's `isEqual` is a test for identity, like the
>>> `===` in Swift. So when you ask "is `a` NOT the same object in memory as
>>> `b`?" the object returns "true" because they are indeed not the same object.
>>>
>>> class Foo:NSObject {
>>>
>>> let name:String
>>>
>>>
>>> init(name:String) {
>>>
>>> self.name = name
>>>
>>> }
>>>
>>>
>>> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>>>
>>> guard type(of:lhs) == type(of:rhs) else { return false }
>>>
>>> return lhs.name == rhs.name
>>>
>>> }
>>>
>>>
>>> public static func !=(lhs: Foo, rhs: Foo) -> Bool {
>>>
>>> guard type(of:lhs) == type(of:rhs) else { return false }
>>>
>>> return lhs.name != rhs.name
>>>
>>> }
>>>
>>> }
>>>
>>>
>>> let a = Foo(name: "bar")
>>>
>>> let b = Foo(name: "bar")
>>>
>>>
>>> print(a == b) // true
>>>
>>> print(a != b) // false
>>>
>>> On Tue, Apr 18, 2017 at 7:33 PM, Zhao Xin via swift-users <
>>> swift-users@swift.org> wrote:
>>>
>>>> Sample 1: both `==` and `!=` is true.
>>>>
>>>> import Foundation
>>>>
>>>>
>>>> class Foo:NSObject {
>>>>
>>>> let name:String
>>>>
>>>>
>>>> init(name:String) {
>>>>
>>>> self.name = name
>>>>
>>>> }
>>>>
>>>>
>>>> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>>>>
>>>> guard type(of:lhs) == type(of:rhs) else { return false }
>>>>
>>>> return lhs.name == rhs.name
>>>>
>>>> }
>>>>
>>>> }
>>>>
>>>>
>>>> let a = Foo(name: "bar")
>>>>
>>>> let b = Foo(name: "bar")
>>>>
>>>>
>>>> print(a == b) // true
>>>>
>>>> print(a != b) // true
>>>>
>>>> Sample 2: Add above code to a do-block, behavior changes to expect
>>>>
>>>> do {
>>>>
>>>> class Foo:NSObject {
>>>>
>>>> let name:String
>>>>
>>>>
>>>>
>>>> init(name:String) {
>>>>
>>>> self.name = name
>>>>
>>>> }
>>>>
>>>>
>>>>
>>>> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>>>>
>>>> guard type(of:lhs) == type(of:rhs) else { return false }
>>>>
>>>> return lhs.name == rhs.name
>>>>
>>>> }
>>>>
>>>> }
>>>>
>>>>
>>>>
>>>> let a = Foo(name: "bar")
>>>>
>>>> let b = Foo(name: "bar")
>>>>
>>>>
>>>>
>>>> print(a == b) // false
>>>>
>>>> print(a != b) // true
>>>>
>>>> }
>>>>
>>>> Sample 3: A little investigation shows that `==` didn't call NSObject's
>>>> `func isEqual(_ object: Any?) -> Bool` but `!=` did.
>>>>
>>>> class Foo:NSObject {
>>>>
>>>> let name:String
>>>>
>>>>
>>>>
>>>> init(name:String) {
>>>>
>>>> self.name = name
>>>>
>>>> }
>>>>
>>>>
>>>>
>>>> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>>>>
>>>> guard type(of:lhs) == type(of:rhs) else { return false }
>>>>
>>>> return lhs.name == rhs.name
>>>>
>>>> }
>>>>
>>>>
>>>>
>>>> override func isEqual(to object: Any?) -> Bool {
>>>>
>>>> print("111")
>>>>
>>>> return super.isEqual(to: object)
>>>>
>>>> }
>>>>
>>>>
>>>>
>>>> override func isEqual(_ object: Any?) -> Bool {
>>>>
>>>> print("")
>>>>
>>>> return super.isEqual(object)
>>>>
>>>> }
>>>>
>>>> }
>>>>
>>>>
>>>> let a = Foo(name: "bar")
>>>>
>>>> let b = Foo(name: "bar")
>>>>
>>>>
>>>> print(a == b) // true
>>>>
>>>> print(a != b) // , true
>>>>
>>>> print(!(a == b)) // false
>>>>
>>>>
>>>> So I am wondering what is the future? Will we keep on using `isEqual(_
>>>>  object: Any?)` with class that inherits `NSObject`, or we are trying
>>>> to drop it?
>>>>
>>>> Xcode  8.3.1 (8E1000a), 3.1 (swiftlang-802.0.51 clang-802.0.41), macOS 
>>>> 10.12.4
>>>> (16E195)
>>>>
>>>> Zhaoxin
>>>>
>>>> ___
>>>> swift-users mailing list
>>>> swift-users@swift.org
>>>> https://lists.swift.org/mailman/listinfo/swift-users
>>>>
>>>>
>>>
>>>
>>> --
>>> Nate Birkholz
>>>
>>
>>
>
>
> --
> Nate Birkholz
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] odd `==` `!=` behavior with class that inherits `NSObject`

2017-04-18 Thread Zhao Xin via swift-users
Everyone should notice that in the do-block (Sample 2). The result is just
opposite of the code out of it (Sample 1). Or say, out the do-block, Swift
calls `==` directly. In the do-block, Swift just call `isEqual(_)` instead
of `==`.

That is the inconsistency I am confused.

Zhaoxin

On Wed, Apr 19, 2017 at 10:33 AM, Zhao Xin  wrote:

> Sample 1: both `==` and `!=` is true.
>
> import Foundation
>
>
> class Foo:NSObject {
>
> let name:String
>
>
> init(name:String) {
>
> self.name = name
>
> }
>
>
> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>
> guard type(of:lhs) == type(of:rhs) else { return false }
>
> return lhs.name == rhs.name
>
> }
>
> }
>
>
> let a = Foo(name: "bar")
>
> let b = Foo(name: "bar")
>
>
> print(a == b) // true
>
> print(a != b) // true
>
> Sample 2: Add above code to a do-block, behavior changes to expect
>
> do {
>
> class Foo:NSObject {
>
> let name:String
>
>
>
> init(name:String) {
>
> self.name = name
>
> }
>
>
>
> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>
> guard type(of:lhs) == type(of:rhs) else { return false }
>
> return lhs.name == rhs.name
>
> }
>
> }
>
>
>
> let a = Foo(name: "bar")
>
> let b = Foo(name: "bar")
>
>
>
> print(a == b) // false
>
> print(a != b) // true
>
> }
>
> Sample 3: A little investigation shows that `==` didn't call NSObject's `
> func isEqual(_ object: Any?) -> Bool` but `!=` did.
>
> class Foo:NSObject {
>
> let name:String
>
>
>
> init(name:String) {
>
> self.name = name
>
> }
>
>
>
> public static func ==(lhs: Foo, rhs: Foo) -> Bool {
>
> guard type(of:lhs) == type(of:rhs) else { return false }
>
> return lhs.name == rhs.name
>
> }
>
>
>
> override func isEqual(to object: Any?) -> Bool {
>
> print("111")
>
> return super.isEqual(to: object)
>
> }
>
>
>
> override func isEqual(_ object: Any?) -> Bool {
>
> print("")
>
> return super.isEqual(object)
>
> }
>
> }
>
>
> let a = Foo(name: "bar")
>
> let b = Foo(name: "bar")
>
>
> print(a == b) // true
>
> print(a != b) // , true
>
> print(!(a == b)) // false
>
>
> So I am wondering what is the future? Will we keep on using `isEqual(_
>  object: Any?)` with class that inherits `NSObject`, or we are trying to
> drop it?
>
> Xcode  8.3.1 (8E1000a), 3.1 (swiftlang-802.0.51 clang-802.0.41), macOS 10.12.4
> (16E195)
>
> Zhaoxin
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] odd `==` `!=` behavior with class that inherits `NSObject`

2017-04-18 Thread Zhao Xin via swift-users
Sample 1: both `==` and `!=` is true.

import Foundation


class Foo:NSObject {

let name:String


init(name:String) {

self.name = name

}


public static func ==(lhs: Foo, rhs: Foo) -> Bool {

guard type(of:lhs) == type(of:rhs) else { return false }

return lhs.name == rhs.name

}

}


let a = Foo(name: "bar")

let b = Foo(name: "bar")


print(a == b) // true

print(a != b) // true

Sample 2: Add above code to a do-block, behavior changes to expect

do {

class Foo:NSObject {

let name:String



init(name:String) {

self.name = name

}



public static func ==(lhs: Foo, rhs: Foo) -> Bool {

guard type(of:lhs) == type(of:rhs) else { return false }

return lhs.name == rhs.name

}

}



let a = Foo(name: "bar")

let b = Foo(name: "bar")



print(a == b) // false

print(a != b) // true

}

Sample 3: A little investigation shows that `==` didn't call NSObject's `
func isEqual(_ object: Any?) -> Bool` but `!=` did.

class Foo:NSObject {

let name:String



init(name:String) {

self.name = name

}



public static func ==(lhs: Foo, rhs: Foo) -> Bool {

guard type(of:lhs) == type(of:rhs) else { return false }

return lhs.name == rhs.name

}



override func isEqual(to object: Any?) -> Bool {

print("111")

return super.isEqual(to: object)

}



override func isEqual(_ object: Any?) -> Bool {

print("")

return super.isEqual(object)

}

}


let a = Foo(name: "bar")

let b = Foo(name: "bar")


print(a == b) // true

print(a != b) // , true

print(!(a == b)) // false


So I am wondering what is the future? Will we keep on using `isEqual(_
 object: Any?)` with class that inherits `NSObject`, or we are trying to
drop it?

Xcode  8.3.1 (8E1000a), 3.1 (swiftlang-802.0.51 clang-802.0.41), macOS 10.12.4
(16E195)

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


Re: [swift-users] Swift 3.1 String(

2017-04-05 Thread Zhao Xin via swift-users
I always use `NSLog("Update name for user %@", fbUser)`. Is `Log.info` your
own implementation?

Zhaoxin


On Wed, Apr 5, 2017 at 10:26 PM, Maxim Veksler via swift-users <
swift-users@swift.org> wrote:

> Hi,
>
> Swift 3.1 compiler seems to introduces a new complier warning regarding
> String(describing: )
>
> So this line:
>
> Log.info("Update name for user \(fbUser)")
>
>
> Produces the warning: "note: use 'String(describing:)' to silence this
> warning"
>
>
> and becomes this line
>
> Log.info("Update name for user \(String(describing: fbUser))")
>
>
> This new syntax is not very sexy, especially for logging. Any suggestions,
> possibility on the API end of Log to make this warning go away? or write it
> differently.
>
> ___
> 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 composition results in EXC_BAD_ACCESS

2017-04-03 Thread Zhao Xin via swift-users
Why not making State as a class? EffectiveState should be subclass of State.

Zhaoxin

On Mon, Apr 3, 2017 at 11:08 PM, Rudolf Adamkovič via swift-users <
swift-users@swift.org> wrote:

> On 3 Apr 2017, at 16:48, Adrian Zubarev 
> wrote:
>
> Why do you cast against an existential in first place?
>
>
> To avoid force-unwrap at the end here:
>
> class Store {
>
> var state: State
>
> // ...
>
> func processScheduledActions() {
>
> guard var effectfulState = state as? Effectful else {
> return
> }
>
> while let actions = effectfulState.scheduledActions.flush() {
> for action in actions {
> delegate?.store(self, didRequest: action)
> }
> }
>
> state = effectfulState as! State
>
>
> }
>
> }
>
> Thank you!
>
> 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] Set with element of NSObject subclasses didn't work as expected

2017-03-28 Thread Zhao Xin via swift-users
Please see the code first.

import Foundation


class Foo:Hashable {

let value:Int



public var hashValue: Int { return value }

public static func ==(lhs: Foo, rhs: Foo) -> Bool {

return lhs.value == rhs.value

}



init(_ value:Int) {

self.value = value

}

}


let fooSetA:Set = [Foo(8), Foo(9)]

let fooSetB:Set = [Foo(9), Foo(10)]

let fooResultC = fooSetA.intersection(fooSetB) // {{value 9}}

let fooResultD = fooSetA.subtracting(fooSetB) // {{value 8}}



class Bar:NSObject {

let value:Int



override public var hashValue: Int { return value }

public static func ==(lhs: Bar, rhs: Bar) -> Bool {

return lhs.value == rhs.value

}



init(_ value:Int) {

self.value = value

}

}


let barSetA:Set = [Bar(8), Bar(9)]

let barSetB:Set = [Bar(9), Bar(10)]

let barResultC = barSetA.intersection(barSetB) // Set([])

let barResultD = barSetA.subtracting(barSetB) // {{NSObject, value 9},
{NSObject, value 8}}


Behaviors of `func intersection(Set)` and `func
subtracting(Set)` were different between normal Swift class
and NSObject subclasses. I had thought they should be the same. It seemed
that Set relied on addresses of NSObject instances instead of
their hashValues. That made the Set useless.

Swift version: 3.1 (swiftlang-802.0.48 clang-802.0.48)
Xcode 8.3 (8E162)

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


Re: [swift-users] @noReturn

2017-03-24 Thread Zhao Xin via swift-users
Change you `func findReasonAndTerminate()` to `func
findReasonAndTerminate() -> String`.
Then you can use `fatalError(func findReasonAndTerminate())`.

Zhaoxin

On Fri, Mar 24, 2017 at 5:02 PM, Rien via swift-users  wrote:

> Is there any way to mark a function as “no return”?
>
> Reason: The compiler generates an error when the else block from a guard
> does not terminate the execution by either a return or a fatalError. I want
> to call out to a function and raise the fatalError in that function.
>
> func findReasonAndTerminate() {
>let reason: String = ….
>fatalError(reason)
> }
>
> main.swift:
>
> guard let data = buildData() else { findReasonAndTerminate() }
>
>
> Currently the work around is to add another fatalError like this:
>
> guard let data = buildData() else { findReasonAndTerminate(); fatalError }
>
>
> but it would be nice to have some attribute like @noReturn:
>
> @noReturn
> func findReasonAndTerminate() { … }
>
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl
>
>
>
>
>
> ___
> 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] Generic and Nested Types

2017-03-23 Thread Zhao Xin via swift-users
Which you?

Zhaoxin

On Thu, Mar 23, 2017 at 4:55 PM, Седых Александр via swift-users <
swift-users@swift.org> wrote:

> Hello. Please explain me, why we can't make Nested Types in Generic 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] How to pass a protocol as parameter, without using @objc?

2017-03-14 Thread Zhao Xin via swift-users
Great!

Zhaoxin

On Tue, Mar 14, 2017 at 2:15 PM, Bruno Macabeus via swift-users <
swift-users@swift.org> wrote:

> I found the solution. I need use a closure.
> I updated the gist: https://gist.github.com/brunomacabeusbr/
> eea343bb9119b96eed3393e41dcda0c9
>
> 2017-03-13 1:38 GMT-03:00 Bruno Macabeus :
>
>> Hello,
>>
>> I wrote a gist to list all classes that subscribers a protocol:
>> https://gist.github.com/brunomacabeusbr/eea343bb9119b96eed3393e41dcda0c9
>> It work, but, I could not pass a protocol as parameter, then, I need
>> wrote one function each time I need to list class from different
>> protocol.
>> I know how to pass a protocol using @obcj
>> , but I can't use @obcj,
>> because my protocols have property.
>>
>
>
> ___
> 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] OptionSet as Sequence

2017-03-12 Thread Zhao Xin via swift-users
I don't see the needs to call `for domain in domains` with `domains:OptionSet`.
If a parameter want an OptionSet, why not just use`domains` directly
instead of `domain`?

Zhaoxin

On Mon, Mar 13, 2017 at 12:09 AM, J.E. Schotsman via swift-users <
swift-users@swift.org> wrote:

> Hello,
>
> Recently I wrote code like this:
>
> let domains:[FileManager.SearchPathDomainMask] = [.userDomainMask,
> .localDomainMask, .networkDomainMask]
> for domain in domains { … }
>
> But I would prefer this:
>
> let domains:FileManager.SearchPathDomainMask = 
> [.userDomainMask,.localDomainMask,
> .networkDomainMask]
> for domain in domains { … }
>
> This requires this OptionSet to conform to Sequence.
> Would it be possible to generically conform all OptionSets with
> RawValue:IntegerArithmetic to Sequence?
> I’ve tried but it seems to be tricky.
>
> Jan 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] Unexpected results when using String.CharacterView.Index

2017-03-09 Thread Zhao Xin via swift-users
Thanks a lot, Ole. I understand now.

Zhaoxin

On Thu, Mar 9, 2017 at 7:54 PM, Ole Begemann <o...@oleb.net> wrote:

> On 09/03/2017 08:27, Zhao Xin via swift-users wrote:
>
>> When using subscript of `String.CharacterView`, I got an unexpected error.
>>
>> fatal error: Can't form a Character from an empty String
>>
>> func test() {
>> let s = "Original Script:"
>> let cs = s.characters
>> //let startIndex = cs.startIndex
>> let nextIndex = "Original ?".characters.endIndex
>> let nextCharacter = cs[nextIndex]// above error
>> }
>>
>> test()
>>
>
> First of all, it's not guaranteed that an index derived from one string
> can be used to subscript another string. Don't rely on that.
>
> endIndex is also different, and this is why you're seeing a crash here.
> Let's inspect nextIndex with dump(nextIndex):
>
> ▿ Swift.String.CharacterView.Index
>   ▿ _base: Swift.String.UnicodeScalarView.Index
> - _position: 10
>   - _countUTF16: 0
>
> You see that _countUTF16 is 0, i.e. internally, String.CharacterView
> assigns its endIndex a length of 0 (in terms of UTF-16 code units). This is
> why it traps when you use the index for subscripting. The endIndex is not a
> valid index for subscripting, not for the string it was derived from and
> not for any other string.
>
> ​However, if I chose​ another way to get the nextIndex. It works.
>>
>> functest() {
>> let s = "Original Script:"
>> let cs = s.characters
>> let startIndex = cs.startIndex
>> //let nextIndex = "Original ?".characters.endIndex
>> let nextIndex01 = cs.index(startIndex, offsetBy: "Original
>> ?".characters.count)
>> let nextCharacter = cs[nextIndex01]
>> }
>>
>> test()
>>
>
> Here, dump(nextIndex01) prints this:
>
> ▿ Swift.String.CharacterView.Index
>   ▿ _base: Swift.String.UnicodeScalarView.Index
> - _position: 10
>   - _countUTF16: 1
>
> Notice that _countUTF16 is 1, so it looks like a valid index from the
> perspective of cs. But again, don't rely on this! The results of
> subscripting a collection with an index derived from another collection are
> undefined unless the collection explicitly documents otherwise.
>
> Further more, I compared the two `nextIndex`. They were equal.
>>
>> functest() {
>> let s = "Original Script:"
>> let cs = s.characters
>> let startIndex = cs.startIndex
>> let nextIndex = "Original ?".characters.endIndex
>> let nextIndex01 = cs.index(startIndex, offsetBy: "Original
>> ?".characters.count)
>> let nextCharacter = cs[nextIndex01]
>> print(nextIndex01 == nextIndex) // true
>> }
>>
>> test()
>>
>
> It looks like String.Index only takes the position into account to
> determine equality, not its _countUTF16. This makes sense for the way
> endIndex and index(_:offsetBy:) are implemented. After all, nextIndex and
> nextIndex01 _should be equal_. It would certainly be possible to implement
> it differently (where endIndex and index(_:offsetBy:) returned identical
> indices, including _countUTF16:) and I don't know why the stdlib team chose
> to do it this way (maybe performance?).
>
> In any case, much of this implementation may change with the work going
> into strings for Swift 4.
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Unexpected results when using String.CharacterView.Index

2017-03-08 Thread Zhao Xin via swift-users
When using subscript of `String.CharacterView`, I got an unexpected error.

fatal error: Can't form a Character from an empty String


func test() {

let s = "Original Script:"

let cs = s.characters

//let startIndex = cs.startIndex

let nextIndex = "Original ?".characters.endIndex

let nextCharacter = cs[nextIndex]// above error

}


test()

​However, if I chose​ another way to get the nextIndex. It works.

func test() {

let s = "Original Script:"

let cs = s.characters

let startIndex = cs.startIndex

//let nextIndex = "Original ?".characters.endIndex

let nextIndex01 = cs.index(startIndex, offsetBy: "Original ?".characters
.count)

let nextCharacter = cs[nextIndex01]

}


test()

Further more, I compared the two `nextIndex`. They were equal.

func test() {

let s = "Original Script:"

let cs = s.characters

let startIndex = cs.startIndex

let nextIndex = "Original ?".characters.endIndex

let nextIndex01 = cs.index(startIndex, offsetBy: "Original ?".characters
.count)

let nextCharacter = cs[nextIndex01]



print(nextIndex01 == nextIndex) // true

}


test()


So I wonder, is there a bug here?


Xcode 8.2.1 (8C1002), Swift 3.0.2


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


Re: [swift-users] Is this really a race condition?

2017-03-02 Thread Zhao Xin via swift-users
I am sorry if this bothers you. I just put the original code in Xcode and
it works. Anyone knows why this works in Xcode or in macOS? I thought it
should show the same warnings as Linux.

Zhaoxin

On Fri, Mar 3, 2017 at 2:51 AM, Edward Connell via swift-users <
swift-users@swift.org> wrote:

> Hi Guillaume,
> There is still a race condition report, but I think maybe we are almost
> there. I had to modify your example because it didn't quite build, and a
> loop to do it twice since it randomly complains if you only do it once.
> Btw, this is on Linux.
> The warning is triggered when deinitialize is called. It wasn't in your
> example, but it seems that it is required since the Elements are not a
> trivial type like Int.
>
> Thanks, Ed
>
> for _ in 0..<2 {
> let count = 1000
> let items = UnsafeMutablePointer<[UInt8]?>.allocate(capacity: count)
> items.initialize(to: nil, count: count)
>
> DispatchQueue.concurrentPerform(iterations: count) {
> items[$0] = [UInt8](repeating: 7, count: 10)
> }
>
> items.deinitialize(count: count)
> items.deallocate(capacity: count)
> }
>
> ==
> WARNING: ThreadSanitizer: data race (pid=24076)
>   Write of size 8 at 0x7d0c5fa0 by main thread:
> #0 free  (libtsan.so.0+0x00025819)
> #1 _TwXxOs31_ClosedRangeIndexRepresentation  (libswiftCore.so+
> 0x0027e071)
>
>   Previous write of size 8 at 0x7d0c5fa0 by thread T20:
> #0 malloc  (libtsan.so.0+0x000254a3)
> #1 swift_slowAlloc  (libswiftCore.so+0x002ee3e5)
>
>   Thread T20 (tid=24288, running) created by main thread at:
> #0 pthread_create  (libtsan.so.0+0x00027577)
> #1 manager_workqueue_additem /home/buildnode/disk2/
> workspace/oss-swift-3.0-package-linux-ubuntu-16_04/
> swift-corelibs-libdispatch/libpwq/src/posix/manager.c:815 (libdispatch.so+
> 0x0007c6b1)
>
> SUMMARY: ThreadSanitizer: data race ??:0 __interceptor_free
> ==
>
>
> ThreadSanitizer: reported 1 warnings
>
>
>
> On Wed, Mar 1, 2017 at 6:48 PM, Edward Connell 
> wrote:
>
>> Ahh! thank you. That makes sense.
>>
>> On Wed, Mar 1, 2017 at 3:29 PM, Guillaume Lessard <
>> gless...@tffenterprises.com> wrote:
>>
>>>
>>> > On Mar 1, 2017, at 3:21 PM, Edward Connell via swift-users <
>>> swift-users@swift.org> wrote:
>>> >
>>> > The thread sanitizer on Linux is reporting that I have race conditions
>>> in libswiftcore. I eliminated enough code down to this trivial example. Is
>>> there really a race condition here or are these bogus errors?
>>> >
>>> >   let count = 1000
>>> >   var items = [[UInt8]?](repeating: nil, count: count)
>>> >
>>> >   DispatchQueue.concurrentPerform(iterations: count) {
>>> >   items[$0] = [UInt8](repeating: 7, count: 10)
>>> >   }
>>> >
>>> > My real scenario is retrieving data asynchronously, so I just threw in
>>> a buffer assignment.
>>>
>>> The assignments to array elements are where the race lies.
>>>
>>> I don’t know about the libswiftcore part, but: assigning to a shared
>>> Array concurrently from multiple threads won't work, because of Array's
>>> copy-on-write behaviour. You could do
>>>
>>> let items = UnsafeMutablePointer<[UInt8]?>.allocate(capacity: 1)
>>> items.initialize(to: nil, count: count)
>>>
>>> DispatchQueue.concurrentPerform(iterations: count) {
>>>   items[$0].initialize([UInt8](repeating: 7, count: 10))
>>> }
>>>
>>> // you’ll be able to see here that they’re all initialized
>>>
>>> items.deallocate(capacity: count)
>>>
>>> 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] unowned self in closure in a playground

2017-02-21 Thread Zhao Xin via swift-users
I think you are right on ` lifetime guaranteed to be around until the
method call completes`. But`[unowned self]` released the retain manually in
your code. Just removing `[unowned self]` part, you code will work.

Zhaoxin

On Wed, Feb 22, 2017 at 3:18 AM, Marco S Hyman via swift-users <
swift-users@swift.org> wrote:

> > The following code crashes:
> >
> > class Demo {
> >   var value = 0
> >   lazy var increment: (Int) -> Void = { [unowned self] by in
> > self.value += by
> > print(self.value)
> >   }
> >  }
> >
> > Demo().increment(3)
> > error: Playground execution aborted: error: Execution was interrupted,
> reason: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
>
> value is not a static/class variable.   Without an instance of Demo it
> does not exist.  This seems to work.
>
> class Demo {
>   static var value = 0
>   lazy var increment: (Int) -> Void = { [unowned self] by in
> value += by
> print(value)
>   }
> }
>
> ___
> 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] ambiguous minus operator

2017-02-16 Thread Zhao Xin via swift-users
I don't know if you are using an IDE, but in Xcode. I can just cmd+mouse
left click to see the code headers.

Zhaoxin

On Fri, Feb 17, 2017 at 2:22 AM, Jon Shier via swift-users <
swift-users@swift.org> wrote:

> I’ve had good luck with being able to click the candidates in
> cases like this so Xcode will navigate to those bits of code. However, in
> this case I think the issue is that the candidates weren’t from user code
> but from the standard library, which Xcode has all sorts of issues
> navigating within, seemingly at random.
> As an aside, it would be really cool if, instead of seeing the
> standard library as a compiled module, Xcode could navigate to the relevant
> source code (perhaps optionally). Otherwise I’m stuck either looking at
> documentation (Apple’s docs or swiftdocs) and if that doesn’t help, trying
> to navigate to the relevant code in GitHub. This is especially true for
> things like finding out what the default values defined for functions are,
> as the documentation just shows default, which is useless.
>
>
> Jon
>
> > On Feb 16, 2017, at 1:16 PM, Jordan Rose via swift-users <
> swift-users@swift.org> wrote:
> >
> >> As usual the candidates are unknown.
> >
> > Just on this particular note, this is a terrible presentation issue and
> totally something we Apple people need to fix in Xcode, but you can usually
> see what the candidates were in the build log.
> >
> > Jordan
> >
> >
> >> On Feb 16, 2017, at 07:56, J.E. Schotsman via swift-users <
> swift-users@swift.org> wrote:
> >>
> >> Hello,
> >>
> >> I am trying to define an operator that subtracts dispatch times:
> >>
> >> #import Dispatch
> >>
> >> func -( time1: DispatchTime, time2: DispatchTime ) ->
> DispatchTimeInterval
> >>  {
> >>  return DispatchTimeInterval.nanoseconds( time2.uptimeNanoseconds
> - time1.uptimeNanoseconds )
> >>  }
> >>
> >> Compiler says: Ambiguous use of operator ‘-'
> >> Found this candidate
> >> Found this candidate
> >>
> >> As usual the candidates are unknown.
> >>
> >> What am I doing wrong?
> >>
> >> Jan 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
>
> ___
> 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-evolution] for in? optionalCollection {

2017-02-11 Thread Zhao Xin via swift-users
What about just use

test?.forEach { print($0) }

Zhaoxin

On Sat, Feb 11, 2017 at 7:48 PM, Tino Heth via swift-evolution <
swift-evolut...@swift.org> wrote:

> This one started over at swift-users, with a question on how to deal with
> looping over containers that may be nil.
>
> Imho the beauty of the feature is that it's simple enough to be explained
> in the subject line, but here is the "long" story:
>
> let test: [Int]? = nil
>
> // this is possible now
> if let test = test {
> for i in test {
> print(i)
> }
> }
>
> // how it could be written with a modified keyword
> for i in? test {
> print(i)
> }
>
> I've been thinking "in?" had been brought up long ago, but as I haven't
> found such a proposal, I probably confused it with the cancelled plan to
> write one on my own (or I just was to stupid to search ;-).
>
> Syntactic sugar like this is definitely nothing that has priority now, but
> discussing it shouldn't be a big distraction — and if it turns into a
> proposal that as well survives review, it might be even simple enough to
> act as a trigger for me to finally get my hands on some real work for Swift
> ;-)
>
> - Tino
>
> ___
> swift-evolution mailing list
> swift-evolut...@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] EnumerateUsingObjects in Swift

2017-01-25 Thread Zhao Xin via swift-users
Can you check the version of you Swift? Your code works in Xcode 8.2.1
(8C1002), Swift 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)

Zhaoxin

On Thu, Jan 26, 2017 at 2:49 AM, Doug Hill  wrote:

> OK, I just tried testing this code in my app and a Swift playground. I
> also tried a variation on the initializer just for the heck of it. I get
> the following error:
>
> class Test
> {
> var array:[T] = []
> var array2 = [T]()
>
> init() {
> var temp  = self.array as NSArray
> var temp2 = self.array2 as NSArray
> }
> }
>
> *error: cannot convert value of type '[T]' to type 'NSArray' in coercion*
> *var temp = self.array as NSArray*
> *   ~^*
> *error: cannot convert value of type '[T]' to type 'NSArray' in coercion*
> *var temp2 = self.array2 as NSArray*
> *~^*
>
> Are there restrictions on what can be converted to NSArray?
>
> Doug Hill
>
> On Jan 25, 2017, at 9:24 AM, Doug Hill via swift-users <
> swift-users@swift.org> wrote:
>
> Thanks for the help. I'm still trying to figure out how Swift works,
> particularly what the error messages mean. This has been driving me a
> little nuts trying to figure out what is wrong via sometimes cryptic
> errors. Also, it seems like getting generic programming working in Swift is
> more difficult than I'm used to (even than C++!) so this answer helps
> figure out how the compiler works.
>
> Doug Hill
>
>
> On Jan 23, 2017, at 7:04 PM, Zhao Xin  wrote:
>
> It seems to me that you didn't initialize your `myArray` before you
> casted it. That caused the problem.
>
> Zhaoxin
>
> On Tue, Jan 24, 2017 at 9:34 AM, Jon Shier via swift-users <
> swift-users@swift.org> wrote:
>
>> enumerateObjects(options:using:) exists on NSArray in Swift. And I was
>> able to create your generic class just fine:
>>
>> class Test {
>> var array: [T] = []
>>
>> init() {
>> var temp = array as NSArray
>> }
>> }
>>
>>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] EnumerateUsingObjects in Swift

2017-01-23 Thread Zhao Xin via swift-users
It seems to me that you didn't initialize your `myArray` before you casted
it. That caused the problem.

Zhaoxin

On Tue, Jan 24, 2017 at 9:34 AM, Jon Shier via swift-users <
swift-users@swift.org> wrote:

> enumerateObjects(options:using:) exists on NSArray in Swift. And I was
> able to create your generic class just fine:
>
> class Test {
> var array: [T] = []
>
> init() {
> var temp = array as NSArray
> }
> }
>
> I’m not sure what the canonical parallel array enumeration would be, but
> you can do it using concurrentPerform:
>
> let array = [“one”, “two”]
> DispatchQueue.concurrentPerform(iterations: array.count) { index in
> print(array[index])
> }
>
>
> On Jan 23, 2017, at 8:20 PM, Doug Hill via swift-users <
> swift-users@swift.org> wrote:
>
> I'm trying to accomplish the equivalent functionality of -[NSArray
> enumerateUsingObjects:…] in Swift. Doing a Googles search, I see that one
> would need to call the equivalent method on the bridged NSArray version of
> your Swift array:
>
> var myNSArray : NSArray = mySwiftArray as NSArray
>
> Here's the problem I'm running into; I have the following class:
>
> class Tester
> {
> var myArray : [typeA]
>
> init()
> {
> var temp = self. myArray as NSArray
> }
> }
>
> Which produces a compiler error:
>
> 'cannot convert value of type '[typeA]' to type 'NSArray' in coercion'
>
> Ok, this makes some sense since I'm guessing NSArray requires each element
> to to be an NSObject but this array type Array could be a
> non-NSObject.
>
> However, this makes my code harder to write since I now have to make sure
> any array has element type NSObject to use enumerateUsingObjects. Not
> something I can either guarantee or even desire.
>
> The reason I like enumerateUsingObjects is that it supports a functional
> style of programming and is better at creating work items for each object
> by dispatching each array item on multiple cores/processors/threads for me.
> Writing this method myself would require figuring out to pass an object to
> a dispatch invocation. But looking through the swift API's, I don't see any
> GCD method for passing an object to dispatch_sync/async. I see versions of
> these methods that takes a context parameter but then takes a C function
> instead of a block, so not very Swift-like and potentially unsafe.
>
> Does this mean enumerateUsingObjects is generally not all that useful in
> Swift? Are there better alternatives? Any ideas on how best to handle this
> situation would be appreciated.
>
> 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
>
>
___
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 Zhao Xin via swift-users
Wagner, the `extension` of `protocol` is never dynamic. It is `fail safe`.
It means if you don't implement something, the compiler will use the
implementation in the `protocol extension`. As in swift, struct and enum
can also conform protocols.

If you want the other way, you should do it in a base class, not in a
protocol extension.

Zhaoxin

On Tue, Jan 24, 2017 at 4:32 AM, Wagner Truppel via swift-users <
swift-users@swift.org> wrote:

> On 23 Jan 2017, at 19:56, Slava Pestov  wrote:
>
> 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.
>
>
> Yes, that's why I wrote overriding in quotes and also why I tried to use
> the word specialise in place of override. My beef is not really here; this
> really was just a preamble. My issue is with the fact that adding the
> declaration to the protocol doesn't solve the problem despite the fact that
> the property is then supposed to be dynamically dispatched but isn't.
>
> ___
> 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] Compiler should issue a warning when a subclass implementation with default values matches a parent implementation without them

2017-01-23 Thread Zhao Xin via swift-users
I doubt if you could have done that in swift-evolution list. As for an
evolution, it requests that you not only provides the question, but also
must provide the answer and how to implementing in code together.

Zhaoxin

On Mon, Jan 23, 2017 at 6:04 PM, Wagner Truppel via swift-users <
swift-users@swift.org> wrote:

> Right, so several people have agreed with me that a compiler warning is in
> order. My question now is: what’s the best way to get this request to the
> people who can make it happen? swift-dev list? swift-evolution list? Apple
> radar? Suggestions are welcome.
>
> Thanks.
> Wagner
>
>
> > On 9 Jan 2017, at 09:49, David Hart  wrote:
> >
> > I think we need a warning because it is definitely ambiguous and a
> common pitfall for users of an API. The only solution would be for the APIs
> be written so to avoid those ambiguities I think.
> >
> >> On 5 Jan 2017, at 08:58, Rien via swift-users 
> wrote:
> >>
> >> As you know. there is no ambiguity, no warnings needed.
> >> (The parameter is part of the identifier of the function)
> >>
> >> Imo, this request falls into the category “do as I think, not as I say”.
> >>
> >> That is a discussion without end. Personally I am against ANY warnings
> of this kind. The reason is that I want my code to compile warnings free
> (default compiler behaviour) and I do not want an extra pragma in the code
> to instruct the compiler that when I am calling “foo()” I do indeed want to
> call “foo()”.
> >>
> >> Regards,
> >> Rien
> >>
> >> Site: http://balancingrock.nl
> >> Blog: http://swiftrien.blogspot.com
> >> Github: http://github.com/Swiftrien
> >> Project: http://swiftfire.nl
> >>
> >>
> >>
> >>
> >>> On 05 Jan 2017, at 03:29, Wagner Truppel via swift-users <
> swift-users@swift.org> wrote:
> >>>
> >>> Hello,
> >>>
> >>> I wasn’t sure whether to post this message here, at swift-dev, or at
> swift-evolution. so I’ll try here first. Hopefully it will get to the right
> group of people or, if not, someone will point me to the right mailing list.
> >>>
> >>> I came across a situation that boils down to this example:
> >>>
> >>> class Parent {
> >>>  func foo() {
> >>>  print("Parent foo() called")
> >>>  }
> >>> }
> >>>
> >>> class Child: Parent {
> >>>  func foo(x: Int = 0) {
> >>>  print("Child foo() called")
> >>>  }
> >>> }
> >>>
> >>> let c = Child()
> >>> c.foo()  // prints "Parent foo() called"
> >>>
> >>> I understand why this behaves like so, namely, the subclass has a
> method foo(x:) but no direct implementation of foo() so the parent’s
> implementation is invoked rather than the child's. That’s all fine except
> that it is not very intuitive.
> >>>
> >>> I would argue that the expectation is that the search for an
> implementation should start with the subclass (which is does) but should
> look at all possible restrictions of parent implementations, including the
> restriction due to default values.
> >>>
> >>> At the very least, I think the compiler should emit a warning or
> possibly even an error.
> >>>
> >>> Thanks for reading.
> >>> Cheers,
> >>>
> >>> 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
> >
>
> ___
> 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] Bool type and reading and writing operation atomicity

2017-01-19 Thread Zhao Xin via swift-users
You can use the GCD semaphore.
https://developer.apple.com/reference/dispatch/dispatchsemaphore

Or it is always better to consider of using queues if you can.

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW1

Zhaoxin

On Wed, Jan 18, 2017 at 5:53 PM, Dale Myers via swift-users <
swift-users@swift.org> wrote:

> Compiler optimisations are something I completely ignored in my reasoning,
> which as has been pointed out was clearly a mistake.
>
> We will switch to using something that provides atomic operations.
>
> Thanks!
>
> -Original Message-
> From: johanneswe...@apple.com [mailto:johanneswe...@apple.com]
> Sent: 17 January 2017 18:37
> To: Dale Myers 
> Cc: swift-users@swift.org
> Subject: Re: [swift-users] Bool type and reading and writing operation
> atomicity
>
> Hi,
>
> > Put simply, are reading and writing to Bools both atomic operations in
> Swift (3)?
>
> you don't get a guarantee for that as Swift at the moment lacks both, a
> memory and a concurrency model.
>
>
> > Obviously, something reading and then assigning assuming the value
> doesn't change between is not correct, but would something like the
> following be fine:
> >
> >var myBool = false
> >
> >// Thread 1
> >while true {
> >if randomEvent() {
> >myBool = true
> >}
> >}
> >
> >// Thread 2
> >while true {
> >if myBool {
> >print("Was set to true")
> >} else {
> >print("Not set")
> >}
> >}
> >
> >
> > I understand that in thread 2, the value of myBool can change between
> the check and the print statements, but that's fine. What I want to confirm
> for my team is that `myBool` can never be in some weird "third" state?
>
> As far as I know, you don't get a guarantee for that. But worse (and just
> like in C/C++/...) you most importantly don't get the guarantee that Thread
> 2 will ever see the change of Thread 1. The compiler could also optimise
> the code in Thread 2 to
>
> while true {
>// if false {
>// print("Was set to true")
>// } else {
>   print("Not set")
>// }
> }
>
> ie. the compiler could 'prove' that `myBool` is never written (legally)
> and therefore delete all the code that assumes myBool != false.
>
> I'm not saying the compiler is doing this today but AFAIK it could do so
> if it wanted.
>
>
> > From what I can tell, behind the scenes, Bool uses a Builtin.Int1 for
> storage. I can't find the definition for this type anywhere so I can't
> check what it is really doing. My assumption is that it uses something like
> a C++ unsigned char behind the scenes, which would be fine with the above
> code on x86 and ARM as far as I'm aware.
>
> In C/C++ you'd need the new _Atomic variables to get that guarantee.
>
>
> > [...]
>
> Again, I'm not saying the compiler does do that but AFAIK it could do so
> legally. But one of the compiler people can answer these questions much
> better than I can.
>
> Cheers,
>   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] Strange Error about Default values

2017-01-18 Thread Zhao Xin via swift-users
Maybe what you want is

struct S1 {
private var _v = 1
var v:Int {
get {
return self._v
}
}
}

Zhaoxin



On Thu, Jan 19, 2017 at 2:08 AM, Jordan Rose via swift-users <
swift-users@swift.org> wrote:

> It is a terrible error message, though. I've filed SR-3671
>  to improve it. Thanks, LiMing
> (and Adrian).
>
> Jordan
>
>
> On Jan 18, 2017, at 07:29, Adrian Zubarev via swift-users <
> swift-users@swift.org> wrote:
>
> Computed properties do not have any default values. That said, you can
> only use didSet or willSet on properties like yours to observe them or
> remove the default value from the computed property completely to use get
> and set.
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 18. Januar 2017 um 15:06:16, Wang LiMing via swift-users (
> swift-users@swift.org) schrieb:
>
> In latest Xcode(8.2.1), playground
>
> struct S1 {
>   var v = 1 {
> get {   // report Error: Use of unresolved identifier
> ‘get'
>   return self.v.// report Error: Use of unresolved identifier
> ‘self'
>}
> }
>
> I can’t found the reason about the error.
> ___
> 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] Weird protocol behaviour.

2016-12-23 Thread Zhao Xin via swift-users
My previous theory was wrong.

> P is an existential for x: P = … where it is upgraded to the static P in foo

Why it needs to be upgraded? Why not just use `P` as a protocol instead of
a `type`? Xcode error message calls `P` as a type.


Zhaoxin

On Fri, Dec 23, 2016 at 9:03 PM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> I’m not sure what you mean. P is an existential for x: P = … where it is
> upgraded to the static P in foo, but the static P does not conform
> to the existential P, which results in an error described by the OP.
>
> x: P = … here it’s Any any type that conforms to P. Any is a type
> of it’s own, and when existentials will be implemented I’d assume that
> there won’t be any upgrade to P from generic context.
>
> let x: Any = …
>
> foo(x)
> // A == Any which should make foo equivalent to
> // `func foo(_ x: Any)` or the current `func foo(_ x: P)`
>
> Right now we just cannot be explicit about existentials.
>
> Please correct me if I’m wrong. ;)
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 23. Dezember 2016 um 13:47:18, Zhao Xin (owe...@gmail.com) schrieb:
>
> You mis-labelled you problem in your original email.
>
> let x = X() as P // this does not compile. Why?
> foo(x)
>
> The issue is not in line ` let x = X() as P`. It is in line ` foo(x)`,
> `x's type is P`, but `foo(:)` request a parameter type of `A`, not `P`.
>
> `func foo(_ x:A) {}` means, `x` must be `A`, and `A` conforms `P`.
> But not all `P`s are `A`.
>
> Zhaoxin
>
> On Fri, Dec 23, 2016 at 5:26 PM, Adrian Zubarev via swift-users <
> swift-users@swift.org> wrote:
>
>> Whoops, wait a second. Correcting my self here. Copied the wrong url.
>>
>> Here is the proposal I meant. LINK
>> 
>>
>>
>> --
>> Adrian Zubarev
>> Sent with Airmail
>>
>> Am 23. Dezember 2016 um 09:57:49, Adrian Zubarev (
>> adrian.zuba...@devandartist.com) schrieb:
>>
>>
>>-
>>
>>What are you trying to solve here?
>>-
>>
>>Do you heavily rely on what A can be?
>>-
>>
>>Can’t you just write func foo(_ x: P) {} (here P is an *existential*
>>like [in some future] Any)?!
>>-
>>
>>AnyObject is for classes, but you’d get the same result changing X to
>>a class ;)
>>
>> If you want scratch the surface of what happens to protocols in a generic
>> context, you could read our proposal about meta types here
>> 
>> .
>>
>>
>> --
>> Adrian Zubarev
>> Sent with Airmail
>>
>> Am 23. Dezember 2016 um 09:43:34, Mikhail Seriukov via swift-users (
>> swift-users@swift.org) schrieb:
>>
>> No it does not.
>>> You have made a type out of the parameter. It’s no longer a protocol.
>>> IMO the failure here is to understand the difference between a type and
>>> a protocol.
>>> A type (even if empty) is always a combination of storage with functions
>>> (that are assumed to work on the data in storage)
>>> A protocol is just a definition of functions without the accompanying
>>> data.
>>>
>>
>> I see your point.
>> But actually when I write it as  `let x = X() as P` I really mean that I
>> want `x` to be `AnyObject` but conforming to P, not just protocol itself.
>> Is it even possible to downcast it this way?
>>
>> 2016-12-23 14:51 GMT+07:00 Marinus van der Lugt :
>>
>>>
>>> On 22 Dec 2016, at 22:43, Howard Lovatt  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.
>>>
>>>
>>>
>>> No it does not.
>>> You have made a type out of the parameter. It’s no longer a protocol.
>>> IMO the failure here is to understand the difference between a type and
>>> a protocol.
>>> A type (even if empty) is always a combination of storage with functions
>>> (that are assumed to work on the data in storage)
>>> A protocol is just a definition of functions without the accompanying
>>> data.
>>>
>>> Rien.
>>>
>>>
>>>
>>>
>>> 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 

Re: [swift-users] Implicitly capture a mutating self

2016-12-16 Thread Zhao Xin via swift-users
Below code should work:

let blockSize = min(512, count)
let blockCount = (count+blockSize-1)/blockSize

let boxedClosure = { (foo:inout MutableDeviceCollection) -> () in
device.sync { // Launch CUDA kernel
try! fill<<<(blockSize, blockCount)>>>[
.pointer(to: foo), .value(value), .value(Int64(count))
]
}
}

boxedClosure()

Zhaoxin

On Fri, Dec 16, 2016 at 5:12 PM, Richard Wei  wrote:

> The original file’s here:
> https://github.com/rxwei/cuda-swift/blob/master/Sources/
> Warp/CollectionOperations.swift
>
> I’m assuming this change has affected Dispatch users as well. It's not a
> good idea for such high-level APIs to rely on explicit pointers to pass
> mutating self for struct types.
>
> -Richard
>
> > On Dec 16, 2016, at 03:05, Richard Wei  wrote:
> >
> > It’s not the correct choice here :)
> >
> >> On Dec 16, 2016, at 03:04, Rien  wrote:
> >>
> >> Just because it is called “Unsafe” does not mean it is unsafe :-)
> >> It all depends on how you use it.
> >>
> >> Regards,
> >> Rien
> >>
> >> Site: http://balancingrock.nl
> >> Blog: http://swiftrien.blogspot.com
> >> Github: http://github.com/Swiftrien
> >> Project: http://swiftfire.nl
> >>
> >>
> >>
> >>
> >>> On 16 Dec 2016, at 09:52, Richard Wei  wrote:
> >>>
> >>> Zhao, it’s not a class.
> >>>
> >>> Rien, unsafe pointers is the last thing I would ever want to introduce
> in my library…
> >>>
> >>> Capturing self was clean, working perfectly, until Swift 3.0.2.
> >>>
> >>> -Richard
> >>>
>  On Dec 16, 2016, at 02:49, Zhao Xin  wrote:
> 
>  What is the type of self? If it is a class, try [unowned self].
> 
>  Zhaoxin
> 
> 
> 
> 
> 
> 
>  On Fri, Dec 16, 2016 at 4:33 PM, Rien via swift-users <
> swift-users@swift.org> wrote:
>  How about using:
> 
>  UnsafeMutablePointer
> 
>  ?
> 
>  Regards,
>  Rien
> 
>  Site: http://balancingrock.nl
>  Blog: http://swiftrien.blogspot.com
>  Github: http://github.com/Swiftrien
>  Project: http://swiftfire.nl
> 
> 
> 
> 
> > On 16 Dec 2016, at 09:10, Richard Wei via swift-users <
> swift-users@swift.org> wrote:
> >
> > Capturing makes it immutable, which unfortunately can't solve this
> problem.
> >
> > -Richard
> >
> >> On Dec 16, 2016, at 02:05, Zhao Xin  wrote:
> >>
> >> I did not test the code. But if you cannot implicitly capture a
> mutating self, you should do it explicitly, right?
> >>
> >> let blockSize = min(512, count)
> >> let blockCount = (count+blockSize-1)/blockSize
> >> device.sync { [self] () -> () in // Launch CUDA kernel
> >>   try! fill<<<(blockSize, blockCount)>>>[
> >>   .pointer(to: ), .value(value), .value(Int64(count))
> >>   ]
> >> }
> >>
> >> Hope above code works.
> >>
> >> Zhaoxin
> >>
> >> On Fri, Dec 16, 2016 at 3:46 PM, Richard Wei via swift-users <
> swift-users@swift.org> wrote:
> >> Hi,
> >>
> >> Swift 3.0.2 seems to have broken my code due to mutating self
> capture. But I have to pass inout self to the closure. Any workaround?
> >>
> >>   let blockSize = min(512, count)
> >>   let blockCount = (count+blockSize-1)/blockSize
> >>   device.sync { // Launch CUDA kernel
> >>   try! fill<<<(blockSize, blockCount)>>>[
> >>   .pointer(to: ), .value(value), .value(Int64(count))
> >>   ]
> >>   }
> >>
> >> 
> >>
> >> -Richard
> >>
> >> ___
> >> 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] Implicitly capture a mutating self

2016-12-16 Thread Zhao Xin via swift-users
What is the type of self? If it is a class, try [unowned self].

Zhaoxin






On Fri, Dec 16, 2016 at 4:33 PM, Rien via swift-users  wrote:

> How about using:
>
> UnsafeMutablePointer
>
> ?
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Swiftrien
> Project: http://swiftfire.nl
>
>
>
>
> > On 16 Dec 2016, at 09:10, Richard Wei via swift-users <
> swift-users@swift.org> wrote:
> >
> > Capturing makes it immutable, which unfortunately can't solve this
> problem.
> >
> > -Richard
> >
> >> On Dec 16, 2016, at 02:05, Zhao Xin  wrote:
> >>
> >> I did not test the code. But if you cannot implicitly capture a
> mutating self, you should do it explicitly, right?
> >>
> >> let blockSize = min(512, count)
> >> let blockCount = (count+blockSize-1)/blockSize
> >> device.sync { [self] () -> () in // Launch CUDA kernel
> >> try! fill<<<(blockSize, blockCount)>>>[
> >> .pointer(to: ), .value(value), .value(Int64(count))
> >> ]
> >> }
> >>
> >> Hope above code works.
> >>
> >> Zhaoxin
> >>
> >> On Fri, Dec 16, 2016 at 3:46 PM, Richard Wei via swift-users <
> swift-users@swift.org> wrote:
> >> Hi,
> >>
> >> Swift 3.0.2 seems to have broken my code due to mutating self capture.
> But I have to pass inout self to the closure. Any workaround?
> >>
> >> let blockSize = min(512, count)
> >> let blockCount = (count+blockSize-1)/blockSize
> >> device.sync { // Launch CUDA kernel
> >> try! fill<<<(blockSize, blockCount)>>>[
> >> .pointer(to: ), .value(value), .value(Int64(count))
> >> ]
> >> }
> >>
> >> 
> >>
> >> -Richard
> >>
> >> ___
> >> 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] Implicitly capture a mutating self

2016-12-16 Thread Zhao Xin via swift-users
I did not test the code. But if you cannot implicitly capture a mutating
self, you should do it explicitly, right?

let blockSize = min(512, count)
let blockCount = (count+blockSize-1)/blockSize
device.sync { *[self] () -> () in* // Launch CUDA kernel
try! fill<<<(blockSize, blockCount)>>>[
.pointer(to: ), .value(value), .value(Int64(count))
]
}

Hope above code works.

Zhaoxin

On Fri, Dec 16, 2016 at 3:46 PM, Richard Wei via swift-users <
swift-users@swift.org> wrote:

> Hi,
>
> Swift 3.0.2 seems to have broken my code due to mutating self capture. But
> I have to pass inout self to the closure. Any workaround?
>
> let blockSize = min(512, count)
> let blockCount = (count+blockSize-1)/blockSize
> device.sync { // Launch CUDA kernel
> try! fill<<<(blockSize, blockCount)>>>[
> .pointer(to: ), .value(value), .value(Int64(count))
> ]
> }
>
>
> -Richard
>
> ___
> 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] Binary package dependencies

2016-12-02 Thread Zhao Xin via swift-users
You are not wrong and it is on schedule of Swift 4.

Zhaoxin

On Fri, Dec 2, 2016 at 4:05 PM, Georgios Moschovitis via swift-users <
swift-users@swift.org> wrote:

> Hi,
>
> It would be great to be able to depend on 'binary' (i.e. precompiled)
> modules/packages using SPM. This would allow distribution of proprietary
> modules without the underlying source code, which is an important use-case.
>
> AFAIK, this is not possible at the moment, but I would love to be proven
> wrong.
>
> Any thoughts?
>
> -g.
> ___
> 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] Problem with mutable views and COW

2016-11-18 Thread Zhao Xin via swift-users
protocol Copyable {

func copy() -> Self

}


final class Storage:Copyable {



var keys: [String] = []

var values: [Int] = []



func copy() -> Storage {

let s = Storage()

s.keys = keys

s.values = values



return s

}

}


public struct Document:Copyable {



var _storageReference: Storage



public init() {



self._storageReference = Storage()

}



public init(_ values: DocumentValues) {



self._storageReference = values._storageReference

}



public var values: DocumentValues {



get { return DocumentValues(self) }



set { self = Document(newValue) }

}



public func copy() -> Document {

var d = Document()

d._storageReference = _storageReference.copy()



return d

}

}


var document = Document()


let copy = document.copy()


// just assume we already added some values and can mutate safely on a
given index

// mutation in place

document.values[0] = 10 // <--- this will only mutate `document` but not
`copy`


You use `class` property inside `struct`, so the `struct` is no longer
copyable. You have to do it yourself.


Zhaoxin

On Fri, Nov 18, 2016 at 10:09 PM, Adrian Zubarev <
adrian.zuba...@devandartist.com> wrote:

> Ups sorry for CCing the post to the evolution list. That happens from time
> to time. :/
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 18. November 2016 um 15:07:43, Adrian Zubarev (
> adrian.zuba...@devandartist.com) schrieb:
>
> I apologize about the weak/unowned issue I mentioned. I kinda missed that
> portion from the docs Weak references do not affect the result of this
> function..
>
> Okay it’s clear to me now why the result is evaluated as false.
>
> But how do I solve the COW problem for mutable views?
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 18. November 2016 um 15:04:55, Adrian Zubarev (
> adrian.zuba...@devandartist.com) schrieb:
>
> This doesn’t make any sense.
>
> Somewhere from the Swift book:
>
> Weak and unowned references enable one instance in a reference cycle to
> refer to the other instance *without keeping a strong hold on it*. The
> instances can then refer to each other without creating a strong reference
> cycle.
>
> From the sdlib of the function isKnownUniquelyReferenced:
>
> Returns a Boolean value indicating whether the given object is a class
> instance known to have *a single strong reference*.
>
> unowned doesn’t increase the reference count, so the view in the examples
> I showed should have no strong reference to that class instance. The only
> strong reference that exists is from Document. So why exactly is the
> result of the second isKnownUniquelyReferenced call false again?
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
> Am 18. November 2016 um 14:50:57, Zhao Xin (owe...@gmail.com) schrieb:
>
> >Why is the second check false, even if the property is marked as unowned for
> the view?
>
> Please search the mailing list, this is not the first time it comes as a
> new question. Shortly speaking, it is `false` only because you used
> `unowned`. If you you can grantee it always exists. Just use it directly,
> this is what `unowned` for. If you can't grantee that. You should use
> `weak` and check it with `if let` or `if foo == nil`
>
> Zhaoxin
>
>
> On Fri, Nov 18, 2016 at 8:05 PM, Adrian Zubarev via swift-users <
> swift-users@swift.org> wrote:
>
>> Hi there,
>>
>> I just can’t get my head around mutable views and COW.
>>
>> Here is a small example:
>>
>> final class Storage {
>>
>> var keys: [String] = []
>> var values: [Int] = []
>> }
>>
>> public struct Document {
>>
>> var _storageReference: Storage
>>
>> public init() {
>>
>> self._storageReference = Storage()
>> }
>>
>> public init(_ values: DocumentValues) {
>>
>> self._storageReference = values._storageReference
>> }
>>
>> public var values: DocumentValues {
>>
>> get { return DocumentValues(self) }
>>
>> set { self = Document(newValue) }
>> }
>> }
>>
>> public struct DocumentValues : MutableCollection {
>>
>> unowned var _storageReference: Storage
>>
>> init(_ document: Document) {
>>
>> self._storageReference = document._storageReference
>> }
>>
>> public var startIndex: Int {
>>
>> return self._storageReference.keys.startIndex
>> }
>>
>> public var endIndex: Int {
>>
>> return self._storageReference.keys.endIndex
>> }
>>
>> public func index(after i: Int) -> Int {
>>
>> return self._storageReference.keys.index(after: i)
>> }
>>
>> public subscript(position: Int) -> Int {
>>
>> get { return _storageReference.values[position] }
>>
>> set { self._storageReference.values[position] = newValue } // That 
>> will break COW
>> }
>> }
>>
>> First of all the _storageReference property is unowned because I wanted
>> to check the following:
>>
>> var document = 

Re: [swift-users] Problem with mutable views and COW

2016-11-18 Thread Zhao Xin via swift-users
>Why is the second check false, even if the property is marked as unowned for
the view?

Please search the mailing list, this is not the first time it comes as a
new question. Shortly speaking, it is `false` only because you used
`unowned`. If you you can grantee it always exists. Just use it directly,
this is what `unowned` for. If you can't grantee that. You should use
`weak` and check it with `if let` or `if foo == nil`

Zhaoxin


On Fri, Nov 18, 2016 at 8:05 PM, Adrian Zubarev via swift-users <
swift-users@swift.org> wrote:

> Hi there,
>
> I just can’t get my head around mutable views and COW.
>
> Here is a small example:
>
> final class Storage {
>
> var keys: [String] = []
> var values: [Int] = []
> }
>
> public struct Document {
>
> var _storageReference: Storage
>
> public init() {
>
> self._storageReference = Storage()
> }
>
> public init(_ values: DocumentValues) {
>
> self._storageReference = values._storageReference
> }
>
> public var values: DocumentValues {
>
> get { return DocumentValues(self) }
>
> set { self = Document(newValue) }
> }
> }
>
> public struct DocumentValues : MutableCollection {
>
> unowned var _storageReference: Storage
>
> init(_ document: Document) {
>
> self._storageReference = document._storageReference
> }
>
> public var startIndex: Int {
>
> return self._storageReference.keys.startIndex
> }
>
> public var endIndex: Int {
>
> return self._storageReference.keys.endIndex
> }
>
> public func index(after i: Int) -> Int {
>
> return self._storageReference.keys.index(after: i)
> }
>
> public subscript(position: Int) -> Int {
>
> get { return _storageReference.values[position] }
>
> set { self._storageReference.values[position] = newValue } // That 
> will break COW
> }
> }
>
> First of all the _storageReference property is unowned because I wanted
> to check the following:
>
> var document = Document()
>
> print(CFGetRetainCount(document._storageReference)) //=> 2
> print(isKnownUniquelyReferenced(_storageReference)) // true
>
> var values = document.values
>
> print(CFGetRetainCount(values._storageReference)) //=> 2
> print(isKnownUniquelyReferenced(_storageReference)) // false
>
> Why is the second check false, even if the property is marked as unowned
> for the view?
>
> Next up, I don’t have an idea how to correctly COW optimize this view.
> Assume the following scenario:
>
> Scenario A:
>
> var document = Document()
>
> // just assume we already added some values and can mutate safely on a given 
> index
> // mutation in place
> document.values[0] = 10
>
> VS:
>
> Scenario B:
>
> var document = Document()
>
> let copy = document
>
> // just assume we already added some values and can mutate safely on a given 
> index
> // mutation in place
> document.values[0] = 10 // <--- this should only mutate `document` but not 
> `copy`
>
> We could change the subscript setter on the mutable view like this:
>
> set {
>
> if !isKnownUniquelyReferenced(_storageReference) {
>
> self._storageReference = ... // clone
> }
> self._storageReference.values[position] = newValue
> }
>
> There is only one problem here. We’d end up cloning the storage every
> time, because as shown in the very first example, even with unowned the
> function isKnownUniquelyReferenced will return false for scenario A.
>
> Any suggestions?
>
> PS: In general I also wouldn’t want to use unowned because the view
> should be able to outlive it’s parent.
>
>
>
> --
> Adrian Zubarev
> Sent with Airmail
>
>
> ___
> 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] minimum deployment target

2016-11-14 Thread Zhao Xin via swift-users
Maybe you should ask this question in
https://forums.developer.apple.com/welcome

Zhaoxin

On Mon, Nov 14, 2016 at 6:26 PM, J.E. Schotsman via swift-users <
swift-users@swift.org> wrote:

> Hello,
>
> I have some code that is used in both a project with minimum deployment
> target 10.9 and a project with minimum deployment target 10.11.
> If I check for availability of API’s on the 10.9 project I get warnings on
> the 10.11 project saying these checks are unnecessary.
> Can I conditionalize this check somehow?
>
> Jan 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] if-case syntax ambiguity

2016-11-09 Thread Zhao Xin via swift-users
The `if case` is the same meaning as `switch-case`, so I don't think there
is anything ambitious. For `switch-case`, it is not equal, it is matching.

Zhaoxin

On Wed, Nov 9, 2016 at 7:17 PM, Nicholas Outram via swift-users <
swift-users@swift.org> wrote:

> Hi
>
> I’ve been drilling down on the syntax of enumerated types with associated
> data in the current release version of Swift 3.
> I’ve pasted below a section of a Playground that captures an issue I’d
> like to raise.
>
> In summary:
>
> Consider the following
> enum Vehicle {
>case car(petrol: Bool, sizeCC: Int)
>case plane(engines : Int)
>case other(String)
>case none
> }
> let myJourney : Vehicle = .other("pogo stick")
>
> *Whereas the following is clear*
> if case .other(_) = myJourney
>
> *the following shorthand equivalent is potentially confusing for the sake
> of 3 characters*
> if case .other = myJourney
>
> - In the first case, the presence of the underscore does communicate that
> something is being assigned, but dropped.
> - In the second case, the reader could easily be mislead into thinking
> that = was supposed to be == as there no apparent place to assign anything.
>
> My suggestion would simply be to drop the shorthand as it’s ambiguous?
>
>
> Nick Outram
>
>
>
>
> import Foundation
>
> //: Consider the following enumerated type with associated data
> enum Vehicle {
>case car(petrol: Bool, sizeCC: Int)
>case plane(engines : Int)
>case other(String)
>case none
> }
>
> //: Let's pick an example
> let myJourney : Vehicle = .other("pogo stick")
>
> //: I now want to test what case `myJourney` is.
> //:
> //: We cannot use the `==` operator because `Vehicle` has associated data.
> Instead we use `if case` and *simply drop the associated value* with `_` as
> shown above
> if case .other(_) = myJourney {
>print("Somewhere nice?")
> } else {
>print("Ok, it's a secret?")
> }
> //:The above is clear enough once you get used to the syntax. The `_`
> communicates that a value has been dropped.
> //:
> //: **However**, Swift 3 allows us to drop the parenthesis altogether and
> use the following shorthand:
> if case .other = myJourney {
>print("Somewhere nice?")
> } else {
>print("Ok, it's a secret?")
> }
> //: *Unlike the previous example, I do wonder if this is a language
> feature that needs review?*
> //:
> //: - On face value, reading this code as is there is an assignment
> operator `=` with nothing apparently being assigned.
> //: - It also reads as if `=` should be `==`
>
>
>
>
>
>
> ___
> 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] Localization in Swift.

2016-11-03 Thread Zhao Xin via swift-users
I just uploaded this as a Xcode extension. You can download it here
.
As long as Swift is not supporting this, you can use my Xcode extension.

Zhaoxin

On Thu, Nov 3, 2016 at 10:36 AM, Zhao Xin  wrote:

> Hello everyone. Thanks to you all for replies in this thread.
>
> I am currently working on a Xcode Extension for this purpose. I would like
> to bring it to github in this week. This will be my first Xcode extension,
> also my first github open sourced project.
>
>
> Zhaoxin
>
> On Thu, Nov 3, 2016 at 6:14 AM, Dave Abrahams via swift-users <
> swift-users@swift.org> wrote:
>
>>
>> on Wed Nov 02 2016, Jens Alfke  wrote:
>>
>> >> On Nov 2, 2016, at 12:50 PM, Dave Abrahams via swift-users <
>> swift-users@swift.org> wrote:
>> >>
>> >> In my opinion, we can and must do much better for Swift.  If there's
>> >> something about “%” formatting that you particularly value, I'd like to
>> >> know about it, so I can make sure it's accomodated.
>> >
>> > It offers more control over formatting, like min/max widths, number
>> > base, decimal places, etc. Yes, you can do this in the code inside the
>> > interpolated string, but IMHO it’s awkward because it requires knowing
>> > a bunch of extra methods for string conversion, truncation, etc. It’s
>> > a lot easier for me to remember and type “%x” than it is to remember
>> > and type the method that converts an int to a hex string.
>>
>> In my view this should look like
>>
>>   "... \(x.format(radix: 16, width: 12))... "
>>
>> Where the possible arguments to format() are statically known to the
>> compiler (and code completion!) based on the type of x.
>>
>> >
>> > Also (and more importantly for localization) the formatting details
>> > are part of the localizable format string, not hardwired. One example
>> > of this is formatting currency, where a US localization would use
>> > “$%.2f” but other currencies might call for more or fewer decimal
>> > places.
>>
>> Yep, I'm paying attention to that, thanks.
>>
>> > There are other examples where one might swap format strings for other
>> > purposes like different-width layouts for monospaced/terminal output.
>>
>> I think we can leverage the same mechanisms used for localization to
>> handle those.
>>
>> > There’s also a nonstandard extension used by Cocoa/CF’s formatters,
>> > that allows the parameters to be reordered. (I haven’t used it so I
>> > don’t know the syntax offhand.) This is of course important for
>> > localization, to follow a language’s grammar.
>>
>> Right, that's crucial.
>>
>> > I think these features could be added to interpolation. Just as a
>> > quick idea, maybe a syntax that allows formatting metacharacters to be
>> > added at the start of the interpolation, like “Please pay $\((.2)
>> > total)” where the “(.2) specifies two decimal places, or “The address
>> > is \((x) addr)”.
>>
>> I think the “.format(...)” approach is better, but it's equally
>> important that there are sufficient outside-the-Swift-source knobs for
>> localizers to add language-specific formatting parameters.
>>
>> --
>> -Dave
>> ___
>> 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] Localization in Swift.

2016-11-02 Thread Zhao Xin via swift-users
Hello everyone. Thanks to you all for replies in this thread.

I am currently working on a Xcode Extension for this purpose. I would like
to bring it to github in this week. This will be my first Xcode extension,
also my first github open sourced project.


Zhaoxin

On Thu, Nov 3, 2016 at 6:14 AM, Dave Abrahams via swift-users <
swift-users@swift.org> wrote:

>
> on Wed Nov 02 2016, Jens Alfke  wrote:
>
> >> On Nov 2, 2016, at 12:50 PM, Dave Abrahams via swift-users <
> swift-users@swift.org> wrote:
> >>
> >> In my opinion, we can and must do much better for Swift.  If there's
> >> something about “%” formatting that you particularly value, I'd like to
> >> know about it, so I can make sure it's accomodated.
> >
> > It offers more control over formatting, like min/max widths, number
> > base, decimal places, etc. Yes, you can do this in the code inside the
> > interpolated string, but IMHO it’s awkward because it requires knowing
> > a bunch of extra methods for string conversion, truncation, etc. It’s
> > a lot easier for me to remember and type “%x” than it is to remember
> > and type the method that converts an int to a hex string.
>
> In my view this should look like
>
>   "... \(x.format(radix: 16, width: 12))... "
>
> Where the possible arguments to format() are statically known to the
> compiler (and code completion!) based on the type of x.
>
> >
> > Also (and more importantly for localization) the formatting details
> > are part of the localizable format string, not hardwired. One example
> > of this is formatting currency, where a US localization would use
> > “$%.2f” but other currencies might call for more or fewer decimal
> > places.
>
> Yep, I'm paying attention to that, thanks.
>
> > There are other examples where one might swap format strings for other
> > purposes like different-width layouts for monospaced/terminal output.
>
> I think we can leverage the same mechanisms used for localization to
> handle those.
>
> > There’s also a nonstandard extension used by Cocoa/CF’s formatters,
> > that allows the parameters to be reordered. (I haven’t used it so I
> > don’t know the syntax offhand.) This is of course important for
> > localization, to follow a language’s grammar.
>
> Right, that's crucial.
>
> > I think these features could be added to interpolation. Just as a
> > quick idea, maybe a syntax that allows formatting metacharacters to be
> > added at the start of the interpolation, like “Please pay $\((.2)
> > total)” where the “(.2) specifies two decimal places, or “The address
> > is \((x) addr)”.
>
> I think the “.format(...)” approach is better, but it's equally
> important that there are sufficient outside-the-Swift-source knobs for
> localizers to add language-specific formatting parameters.
>
> --
> -Dave
> ___
> 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] Localization in Swift.

2016-11-01 Thread Zhao Xin via swift-users
I am not talking to eliminate "%" style function. I am talking to add more
compatibility to `NSLocalizedString` with `\(foo)` style. As there is no
rule forbidding that, it should work. If someone doesn't need the flexible
parts, why he has to use the complicated way?

Zhaoxin

On Wed, Nov 2, 2016 at 1:49 PM, Jens Alfke  wrote:

>
> > On Nov 1, 2016, at 10:40 PM, Zhao Xin  wrote:
> >
> > For example, if I want show the user that I have to ask him to give me
> permission of a folder, the `url.path` has no need to translate.
>
> We’re getting off-topic, but paths do need to be translated, at least on
> Mac systems. The names of many standard folders like “Applications” and
> “Documents” are hardwired to English in the filesystem but are localized in
> the UI. Some application names get localized too (there’s a table in the
> app’s Info.plist that can substitute localized names.)
>
> Anyway, string interpolation is convenient, but I wouldn’t say it should
> be the only way to format strings in Swift; it’s a lot less flexible than
> the C-style “%” substitutions. For comparison, even though C++’s iostreams
> use “<<“ to format strings by concatenation, I still end up using “%” based
> formatting a lot, depending on the use case.
>
> —Jens
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Localization in Swift.

2016-11-01 Thread Zhao Xin via swift-users
The second should be

let says = String.localizedStringWithFormat(NSLocalizedString("
> ​blabla
> %
> ​@
> ​blabla
> ", comment: "
> ​blabla
> "),
> ​String(​
> count
> ​)​
> )


​Zhaoxin​

On Wed, Nov 2, 2016 at 10:50 AM, Zhao Xin <owe...@gmail.com> wrote:

> I think in Swift.
>
> let count = 10
>> let says = NSLocalizedString("
>> ​blabla
>> \(count)
>> ​blabla
>> ", comment: "
>> ​blabla
>> ")
>
>
> ​can be roughly interpreted as
>
> let says = String.localizedStringWithFormat(NSLocalizedString("
>> ​blabla
>> %
>> ​@
>> ​blabla
>> ", comment: "
>> ​blabla
>> "), count)
>
>
> ​So if Swift does not want to do much effort on this ​, it could just find
> every localized string that is with  '\(foo)' in `NSLocalizedString` and
> converted to `String.localizedStringWithFormat(NSLocalizedString...`
> internally.
>
> Zhaoxin
>
>
> On Wed, Nov 2, 2016 at 12:08 AM, Jens Alfke <j...@mooseyard.com> wrote:
>
>>
>> > On Nov 1, 2016, at 1:53 AM, Zhao Xin via swift-users <
>> swift-users@swift.org> wrote:
>> >
>> > I began to realize that` \(count)` was not dealed well in localization.
>> The compiler calculated the full string then looking for the translation,
>> instead of looking for the translation first.
>>
>> NSLocalizedString was designed (in the 1990s) to be used with methods
>> like String(format:…) that take printf-style “%”-substituted format strings.
>> Swift’s string interpolation is obviously a different mechanism entirely.
>>
>> I suspect that Swift interpolation won’t work well for localized strings
>> because the string and the code are so tightly connected. Localization very
>> often needs to change the order of parameters, for instance. It’s also
>> unclear where things like number formatting happen in Swift interpolation;
>> when localizing a string, the conversion needs to be done using the same
>> locale as the string lookup, which might not happen if the string-to-number
>> conversion is separate and uses the default locale.
>>
>> —Jens
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Localization in Swift.

2016-11-01 Thread Zhao Xin via swift-users
I encountered a localization problem today. At first I translated a string
like this.

let count = 10
> let says = NSLocalizedString("It runs \(count) times", comment: "run
> times")


I couldn't get the translation taking effect.

So I open the setting "Localization Debugging" in scheme and get this error:

[strings] ERROR, It runs 10 times not found in table Localizable of bundle
> CFBundle 0x100c01c40 ... (executable, loaded)
> IT RUNS 10 TIMES


I began to realize that` \(count)` was not dealed well in localization. The
compiler calculated the full string then looking for the translation,
instead of looking for the translation first.

I managed to replace my code with

let newSays = String.localizedStringWithFormat(NSLocalizedString("It runs
> %d times", comment: "new run times"), count)


However, I still thing it would be better if we could use \(foo) directly,
as it is more Swift style. Any idea why this can't happen?

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


Re: [swift-users] Will it be better if `fallthrough` works with `label` in nested `switch - case`?

2016-10-14 Thread Zhao Xin via swift-users
I manage to use below work around.

let count = 1


switch count {

case 0, 1:

let buttonId = NSAlertThirdButtonReturn

let shouldFallthrough = { () -> Bool in

switch buttonId {

case NSAlertFirstButtonReturn:

print("do something")

case NSAlertSecondButtonReturn:

print("do something")

case NSAlertThirdButtonReturn:

print("do something")

return true

default:

fatalError()

}



return false

}()

if shouldFallthrough { fallthrough }

default:

print("do extra things")

}

Zhaoxin


On Sat, Oct 15, 2016 at 10:44 AM, Zhao Xin  wrote:

> I thought below code would work. It didn't.
>
> let count = 1
>
>
> outerSwitch: switch count {
>
> case 0, 1:
>
> let buttonId = 0
>
> switch  buttonId {
>
> case NSAlertFirstButtonReturn:
>
> print("do something")
>
> case NSAlertSecondButtonReturn:
>
> print("do something")
>
> case NSAlertThirdButtonReturn:
>
> print("do something")
>
> fallthrough outerSwitch // error here
>
> default:
>
> fatalError()
>
> }
>
> default:
>
> print("do extra things")
>
> }
>
> So I have to use `if - else if - else` instead. I think if `fallthrouh`
> works with `label`, the code will be more elegant.
>
> Zhaoxin
>
>
>
>
>
>
>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


[swift-users] Will it be better if `fallthrough` works with `label` in nested `switch - case`?

2016-10-14 Thread Zhao Xin via swift-users
I thought below code would work. It didn't.

let count = 1


outerSwitch: switch count {

case 0, 1:

let buttonId = 0

switch  buttonId {

case NSAlertFirstButtonReturn:

print("do something")

case NSAlertSecondButtonReturn:

print("do something")

case NSAlertThirdButtonReturn:

print("do something")

fallthrough outerSwitch // error here

default:

fatalError()

}

default:

print("do extra things")

}

So I have to use `if - else if - else` instead. I think if `fallthrouh`
works with `label`, the code will be more elegant.

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


[swift-users] Why can't we get `URL` equal on the same path?

2016-10-14 Thread Zhao Xin via swift-users
As you can see, `URL` is not equal but the `path` is. I wonder why urls do
not equal here?

let url = URL(fileURLWithPath: "foo/bar", isDirectory: false)

let baseURL = url.deletingLastPathComponent()

let newURL = URL(fileURLWithPath: "bar", isDirectory: false, relativeTo:
baseURL)


print(url == newURL) // prints false

print(url.path == newURL.path) // prints true

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


Re: [swift-users] Compiler refuses non-escaping closure calls in nested function

2016-10-10 Thread Zhao Xin via swift-users
Thank you, Ole. Your reply teaches me a lot.

Zhaoxin

On Mon, Oct 10, 2016 at 6:52 PM, Ole Begemann via swift-users <
swift-users@swift.org> wrote:

> The line "let result = closure(n)" is refused by the compiler with the
>> error message "declaration over non closing parameter may allow it to
>> escape".
>>
>> First off, while I know what an escaping or a non-escaping closure is, I
>> find this error message utterly impossible to understand. To begin with,
>> the sentence "non closing parameter" is meaningless to me.
>>
>
> The error message I'm seeing in Xcode 8.0 is "Declaration closing over
> *non-escaping* parameter 'closure' may allow it to escape", so I don't know
> where you're seeing the "non closing parameter". And "non-escaping
> parameter" does make a lot more sense, I think.
>
> In any case, my main function is passed a non-escaping closure. I want
>> to call it from inside it, the compiler is ok with. I want also to call
>> it from a nested function, but the compiler disagrees.
>>
>> I believe the compiler should not complain here. Did I miss anything?
>>
>
> I think the error message is actually quite good, given that the compiler
> apparently is taking some shortcuts to prove that a parameter doesn't
> escape.
>
> By declaring a function that closes over the non-escaping parameter,
> you're creating a situation that *may* allow the non-escaping closure to
> escape, i.e. the compiler can't guarantee anymore that it won't escape. For
> example, you could do assign the `closureDoubled` function to a variable
> that's outside the scope of `mainFunction`:
>
> // Variable outside the scope of mainFunction
> var f: (Int) -> (Int) = { $0 }
>
> func mainFunction(closure: (Int) -> Int) -> Int {
>
> func closureDoubled(_ n: Int) -> Int {
> let result = closure(n)
> return 2*result
> }
>
> // closure would escape here
> f = closureDoubled
> ...
> }
>
> mainFunction { $0 }
> f(5)
>
> If this were allowed, `closure` would be able to escape. I think this
> possibility explains the error message.
>
> Now the compiler *could* of course check for this and I think you're right
> in arguing that it *should* ideally perform more sophisticated checks, but
> since it currently seems to be taking some shortcuts in guaranteeing that a
> parameter doesn't escape, it has to disallow anything it can't verify as
> correct.
>
> Ole
>
> ___
> 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] Compiler refuses non-escaping closure calls in nested function: Bug?

2016-10-10 Thread Zhao Xin via swift-users
> It is just like there were two ways to do the job, you thought it worked
in this way, but it chose the other way. Both ways lead to the same result.

I think it is because the compiler **flatten** your inner function instead
of calculated the result.

The variable scope of `closure` is outside the `func closureDoubled`, so it
is `escaping` from that function. However, since `closure` is defined
outside, there is no place in `func closureDoubled` mark as `@escaping`, so
the compiler asked me to add `@escaping` in the place where it is firstly
defined.

Zhaoxin



On Mon, Oct 10, 2016 at 4:06 PM, Jean-Denis Muys  wrote:

> It seems to me you are shooting while blindfolded.
>
> I changed you code `let result = closure(n)` to `let result = closure(1)`.
> I thought that should eliminate the error. It didn't. The compiler asked me
> to change the whole code as below:
>
>
> Why did you expect changing which argument to send the closure to make any
> difference?
>
> func mainFunction(closure: @escaping (Int) -> Int) -> Int {
>
>
> Sure declaring the closure as escaping shuts up the compiler. At the cost
> of having an escaping closure in a context where the closure is guaranteed
> no to escape. My understanding of the distinction between escaping and non
> escaping is it enables compiler optimisations (in the non escaping case)
> that would not be possible in the general case. Therefore this
> compiler-mandated change kills performance for nothing
>
>
> So I think in `func closureDoubled(_ n: Int) -> Int`, the `closure` is
> escaping other than non-escaping.
>
>
> No. The closure is not escaping. At least as far as I can see. Can you
> point out where it is escaping? Declaring a closure as escaping does not
> make it so. It only *allows* it to escape.
>
> Note that here, “escaping” means escaping the scope where it is declared,
> i.e. the `mainFunction` function. Clearly, it does not.
>
>
>  The result is not calculated inside the function `closureDoubled`, it
> was calculated at `return temp1+temp2`, that is what I think can explain
> the behavior.
>
>
> Where does this speculation comes from? It totally contradicts the story
> that the source code tells. temp1 and temp2 and Int variables that are
> local to `mainFunction `, while `result` is local to the nested function
> `closureDoubled`. Unless you use of the word “result” does not refer to the
> `result` variable. I apologise for the poor choice of variable names that
> made possible this confusion.
>
> I don't know why at first. It just like there were two ways to do the job,
> you thought it worked in this way, but it chose the other way. Both ways
> lead to the same result.
>
>
> You lost me in that sentence. What do the pronouns refer to?
>
> Then I changed your code to
>
>
> yes you totally changed my code by adding a closure parameter to the
> nested function, in which you passed the closure that was passed to the
> outer function.
>
> By doing so, however, you altered significantly my use case. This is
> because the point of having a nested function, as opposed to a separate
> function defined outside the outer function, is for the nested function to
> capture the environment of its containing function.
>
> Of course, this begs the question: this is semantically equivalent, so why
> objecting to that? There are two answers to that question:
>
> 1- preventing a nested function from capturing a local closure is a
> significant limitation which essentially demotes closure from the status of
> first-class citizen. The artificial limitation of expressiveness in the
> language is unwarranted and a serious flaw (if intended. I still believe
> this is a bug)
> 2- A very common pattern for nested functions is to make recursive
> algorithms more memory-efficient by forwarding the recursion to a nested
> function whose parameters are only those values that change during the
> recursion. Other values, such as the parameter you just added in your
> change, if passed as parameters, will only waste stack space since they
> will never change in the recursion. This will also degrade performance
> slightly because the code will have to push this unchanging value to the
> stack every time a recursive call is made.
>
> Note that this was the context where I was bitten by the problem. Of
> course, you could expect a smart compiler to recognise that is doesn’t have
> to push unchanging parameter values onto the stack in recursive calls.
> Similarly, there are smart compiler which recognise terminal recursion and
> transform recursion into iteration. I even encountered in the past (Lisp)
> compilers which automatically transformed simple cases of non-terminal
> recursion into terminal-recursive versions (by adding an accumulator
> parameter), followed by transformation into iterative code. I do not expect
> typical compilers to do that (where “typical” is left undefined, but would
> include GCC, Clang, Swift). This is why I tend to implement my recursive

[swift-users] Is there an equivalence method on `NSArray`'s `func objects(at indexes: IndexSet) -> [Any]` in Array?

2016-10-06 Thread Zhao Xin via swift-users
I managed to do that by using `map` as I didn't find the equivalence.

files.forEach {

var indices = IndexSet()



for index in 0 ..< subtitleFiles.count {

if $0.sn == subtitleFiles[index].sn {

indices.insert(index)

}

}



let subtitles = indices.map { return subtitleFiles[$0] } // get array
at IndexSet

videoSubtitles.updateValue(subtitles, forKey: $0)

indices.reversed().forEach { subtitleFiles.remove(at: $0) } // remove
elements at IndexSet

}


Is there a better way to do that?


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


Re: [swift-users] Any?

2016-09-27 Thread Zhao Xin via swift-users
`Any` is different from `Any?`.  For example, if `Any` is an `Optional`,
`Any?` is an `Optional`.

I
​n you code, since ​`dictionary` subscripts may `return nil`, the `?` is
for that. The `Any` is for the type of the `none-nil return value`.


Zhaoxin

On Tue, Sep 27, 2016 at 6:43 PM, Седых Александр via swift-users <
swift-users@swift.org> wrote:

> Hello. I have little question about type Any on screenshot.
>
> Why we need the type Optional Any
> In book we read, that Any may be any type. And any type is not include
> optionals in self?
>
>
>
>
>
> ___
> 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 anyone please explain this behavior?

2016-09-21 Thread Zhao Xin via swift-users
I suggest you defining the variables before using them like Marco does.
Although from the global variable point of view, both way should be fine.
But the glitch does exist, especially in playground.

Zhaoxin

On Thu, Sep 22, 2016 at 5:59 AM, Marco S Hyman via swift-users <
swift-users@swift.org> wrote:

>
> > On Sep 21, 2016, at 2:22 PM, Jens Persson via swift-users <
> swift-users@swift.org> wrote:
> >
> > // This little Swift program compiles (and runs) fine:
> >
> > func foo() -> Int { return a }
> > let a = 1
> > let b = 2
> > print(foo())
> >
> > But if `foo()` returns `b` instead of `a`, I get this compile time error:
> > "Use of unresolved identifier `b`”
>
> Interesting.  Seems to have something to do with ordering as if you code
> it this way:
>
> let a = 1
> let b = 2
> func foo() -> Int { return b }
> print(foo())
>
> it works fine (Xcode 8 playground).
> ___
> 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] reading keyboard input from xcode playgroud

2016-09-20 Thread Zhao Xin via swift-users
I test you code in command line `swiftc main.swift` and in macOS Command
Line Tool app.

Here is the main.swift:

import Foundation


import Foundation


func input() -> String {

let keyboard  = FileHandle.standardInput

let inputData = keyboard.availableData

let strData   = String(data: inputData, encoding: .utf8)

return strData!

}


func write(_ txt: String) {

print(txt, terminator: "")

}


func read() -> String {

let c = CharacterSet.whitespacesAndNewlines

return input().trimmingCharacters(in: c)

}


/* main program */


write("Enter your name: ")

let s = read()

print("You name is \(s)")


It turns out that the input request was ran before the `write("Enter your
name: ")`. I don't why. Maybe it is a bug?


Here is my output in terminal:


$ swiftc main.swift

$ ./main

abc

Enter your name: You name is abc

$


As you can see, the program asked me to input my name before it showed the
notification. In playground, the situation is alike.


However, if the code is running as a command line tool, created by Xcode ->
Create a new project -> macOS, command line tool, everything works fine.


Zhaoxin

On Sun, Sep 18, 2016 at 9:16 PM, Mr Bee via swift-users <
swift-users@swift.org> wrote:

> Hi all,
>
> Another question. I used to use this snippet to read keyboard input from
> XCode's Playground. And it used to work very well. Today, I just updated my
> XCode to v.8 and Swift v.3. After a little bit modification here and there
> due to Swift 3 incompatibility, I got this code compiled without error. But
> it doesn't work. No keyboard input is taken. It just stucks.
>
> Here's the code:
>
> import Foundation
>
> func input() -> String {
>   let keyboard  = FileHandle.standardInput
>   let inputData = keyboard.availableData
>   let encoding  = String.Encoding(rawValue: String.Encoding.utf8.rawValue)
>   let strData   = String(data: inputData, encoding: encoding)
>   return strData! as String
> }
>
> func write(_ txt: String) {
>   print(txt, terminator: "")
> }
>
> func read() -> String {
>   let c = CharacterSet.whitespacesAndNewlines
>   return input().trimmingCharacters(in: c)
> }
>
> /* main program */
>
> write("Enter your name: ")
> let s = read()
>
> So, does anyone know how to make it works (again)? 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


[swift-users] [swift-user]Unexpected behavior of protocol extension.

2016-09-19 Thread Zhao Xin via swift-users
See below code.

protocol Foo {

func bar()

}


extension Foo {

func bar() {

print("I am bar.")

}

}


class A:Foo {

func output() {

print(type(of:self)) // prints "B".

self.bar() // prints "I am bar."

(self as! B).bar() // prints "I am B."

}

}


class B:A {

func bar() {

print("I am B.")

}

}


let b = B()

b.output()


I thought `self.bar()` would do the same as `(self as! B).bar()`. It
didn't. In my opinion,  `type(of:self) is B.type`, so they should be the
same, shouldn't they?


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


Re: [swift-users] Stored Property on Protocol Extension

2016-09-12 Thread Zhao Xin via swift-users
​I don't know why the limit exists. Technical or on purpose. I hope someone
inside can answer this.

Zhaoxin​

On Mon, Sep 12, 2016 at 11:55 PM, Daniel Dunbar via swift-users <
swift-users@swift.org> wrote:

>
> > On Sep 11, 2016, at 6:12 PM, Tanner Nelson via swift-users <
> swift-users@swift.org> wrote:
> >
> > Hey Swift Users,
> >
> > I was wondering how you all work around not being able to add stored
> properties in extensions (especially protocol extensions).
> >
> > I ran into an issue recently where I needed an internal stored variable
> for a protocol, but I didn't want the conformer to worry about implementing
> the variable.
> >
> > I ended up using something like this to achieve the effect.
> >
> >extension MyProtocol {
> >private var address: String {
> >mutating get {
> >var id = ""
> >withUnsafePointer(to: ) { id = "\($0)"}
> >return id
>
> BTW, you can write `return withUnsafePointer(to: ) { "\($0)" }`
> instead.
>
> >}
> >}
> >
> >var myStoredVar: Bool {
> >mutating get {
> >return _storage[address] ?? false
> >}
> >set {
> >_storage[address] = newValue
> >}
> >}
> >}
> >
> > Obviously not ideal, but I don't see another way to achieve this besides
> subclassing (which has its own problems for my situation).
> >
> > Wondering if anyone has run into this and come up with a better solution
> or other type of work around.
>
> I don't have a better answer to this part.
>
> This particular solution only works if it is ok for `_storage[address]` to
> potentially be reused by a new instance, though (if the old instance is
> deallocated and the new one is allocated in its place).
>
>  - Daniel
>
> >
> > Thanks!
> > Tanner
> > ___
> > 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] Lazy expression is ambiguous?

2016-09-12 Thread Zhao Xin via swift-users
It is not a bug. You must explicitly specify the variable's type if you use
`lazy` keyword. `lazy` means the variable will be initialized later, but
the compiler needs its type right now.

Zhaoxin

On Mon, Sep 12, 2016 at 3:02 PM, Quinn "The Eskimo!" via swift-users <
swift-users@swift.org> wrote:

>
> On 12 Sep 2016, at 06:40, Jacob Bandes-Storch via swift-users <
> swift-users@swift.org> wrote:
>
> > I'd recommend filing a bug at bugs.swift.org.
>
> Agreed.
>
> Also, you can work around this by adding a type.
>
>   lazy var myQ: DispatchQueue = DispatchQueue(label: "Op", attributes:
> .concurrent)
>
> Also, with regards this specific example, be aware that lazy properties
> aren’t guaranteed to be initialised only once.  To quote “The Swift
> Programming Language”:
>
> If a property marked with the `lazy` modified is accessed by multiple
> threads simultaneously and the property has not yet been initialized,
> there is no guarantee that the property will be initialized only once.
>
> I’m struggling to think of a case where that limitation is acceptable in
> the context of a dispatch queue (-:
>
> Share and Enjoy
> --
> Quinn "The Eskimo!"
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
>
>
> ___
> 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] Migrating to Swift 3 using Xcode fails

2016-09-08 Thread Zhao Xin via swift-users
I
​ am confused with your situation. You said, "I’ve migrated one of my
projects to Swift 3 previously, with an earlier beta of Xcode.". Then in
Xcode should not using Swift 2.3. Assuming
​X
​code using 2.3 wrongly, you should use Xcode migration tool again, after
that Xcode will use Swift 3.0. You manually change code will not cause
Xcode using Swift 3.0 automatically.

Zhaoxin​

On Fri, Sep 9, 2016 at 10:26 AM, Saagar Jha  wrote:

> I am aware that there were new proposals, and I’ve been following along
> and manually migrating. The errors are due to Xcode using the Swift 2.3
> compiler, which doesn’t like the new Swift 3 syntax (for example, it’s
> complaining that it can’t find the new types that have the NS- prefix
> dropped). I’m just looking for the flag in build settings that switches the
> compilers.
>
> Saagar Jha
>
>
>
> On Sep 8, 2016, at 16:47, Zhao Xin  wrote:
>
> ​I think you can just use Xcode's tool that you upgrade to Swift 3.0.
> However, I suggest you do a backup of your project first in case this is
> not helpful.
>
> Also, the errors you saw were probably not because of Xcode converted you
> code to 2.3 automatically. It wouldn't do that. The real reason is that in
> Xcode 6 beta6, a lot of Swift 3.0 accepted proposals were implemented and
> released, which made the Swift 3.0 far more different from the previous
> 3.0.
>
> Xcode's migration tool is closed sourced and is not part of Swift. ​If you
> have further questions, I suggest you to ask it in Apple's developer forum.
>
> Zhaoxin
>
> On Fri, Sep 9, 2016 at 5:01 AM, Saagar Jha via swift-users <
> swift-users@swift.org> wrote:
>
>> Hi,
>>
>> I’ve migrated one of my projects to Swift 3 previously, with an earlier
>> beta of Xcode. However, after downloading the GM seed, hundreds of errors
>> pop up in my code, since it appears that Xcode has somehow reverted the
>> compiler back to 2.3. Manually migrating using Edit>Convert>To Current
>> Swift Syntax… always fails, due to the fact that the code had been
>> previously migrated. Is there any way to “manually” migrate the code (i.e.
>> change the compiler settings?)
>>
>> Thanks,
>> Saagar Jha
>>
>>
>>
>>
>> ___
>> 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 Playgrounds Not Included with iiOS 10.0.1 GM

2016-09-08 Thread Zhao Xin via swift-users
It is not on mine after upgrading to GM through OTA. Mine free space is
9.35GB.

I think it can be easily explained. It is not a system app, it appeared in
beta just because it is easily for us to test. It will appear in App Store
when iOS 10 officially released.

Zhaoxin

On Fri, Sep 9, 2016 at 7:25 AM, Erica Sadun via swift-users <
swift-users@swift.org> wrote:

> It is still on my iPad.
>
> As far as I can tell (going by Twitter replies), if you had sufficient
> space for the upgrade (I had about 3.5 gb), it was not removed.
>
> I recommend filing a bug report at bugreport.apple.com
>
> -- E
>
>
> On Sep 8, 2016, at 3:23 PM, Michael Sheaver via swift-users <
> swift-users@swift.org> wrote:
>
> This is just a heads-up for all who might be using/enjoying/playing with
> Swift Playgrounds on the iPad; it has apparently been removed from the GM
> that was released yesterday. There are a couple posts about it in the Apple
> forums, but no definitive answers have been posted as yet. I searched in
> the App Store, and it isn't there yet either.
>
> Michael Sheaver
>
> ___
> 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] 'Error' is ambiguous for type lookup in this context

2016-09-07 Thread Zhao Xin via swift-users
Thank you for all your replies, Shawn.

Zhaoxin

On Thu, Sep 8, 2016 at 12:22 PM, Shawn Erickson <shaw...@gmail.com> wrote:

> You are implementing function defined in the WCSessionDelegate so that
> your AppDelegate can be called by WCSession as things happen. It calls your
> implementation and supplies it with an error is one exists (e.g. an error
> happened).
>
> It doesn't make sense for this function (the one you implement) to throw
> since you aren't returning an error to the caller (WCSession) but instead
> potentially getting an error from the caller (WCSession).
>
> -Shawn
>
> On Wed, Sep 7, 2016 at 8:53 PM Zhao Xin <owe...@gmail.com> wrote:
>
>> I also have a question on this API
>> ​`func session(_ session: WCSession, activationDidCompleteWith
>> activationState: WCSessionActivationState, error: Error?)`. Why did it use
>> `throws`? The other APIs, which use NSError in Objective-C, change to
>> throws in Swift counterpart.
>>
>> Zhaoxin
>>
>> On Thu, Sep 8, 2016 at 10:52 AM, Shawn Erickson <shaw...@gmail.com>
>> wrote:
>>
>>> For one RealmSwift should likely consider changing their enum cases to
>>> use lowerCamelCase like Swift 3 did. Also at some point it should consider
>>> the changes to NSError / Swift.Error bridging.
>>>
>>> -Shawn
>>>
>>> On Wed, Sep 7, 2016 at 7:18 PM Zhao Xin via swift-users <
>>> swift-users@swift.org> wrote:
>>>
>>>> When I use RealmSwift in my project, I got an alert " 'Error' is
>>>> ambiguous for type lookup in this context".
>>>>
>>>> import UIKit
>>>>
>>>> import UserNotifications
>>>>
>>>> import WatchConnectivity
>>>>
>>>> import RealmSwift
>>>>
>>>>
>>>> extension AppDelegate:WCSessionDelegate {
>>>>
>>>> func session(_ session: WCSession, activationDidCompleteWith
>>>> activationState: WCSessionActivationState, error: Error?) {
>>>>
>>>>
>>>> }
>>>>  }
>>>>
>>>>
>>>> I think the reason is that in Swift, Error is a protocol. And in
>>>> RealmSwift, there is a `case Error(NSError)` in `public enum
>>>> RealmCollectionChange`.
>>>>
>>>>
>>>> I managed to eliminate the alert buy change `Error?` to `Swift.Error?`.
>>>> Are there any other ways to fix this?
>>>>
>>>>
>>>> Zhaoxin
>>>> ___
>>>> 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] 'Error' is ambiguous for type lookup in this context

2016-09-07 Thread Zhao Xin via swift-users
I also have a question on this API
​`func session(_ session: WCSession, activationDidCompleteWith
activationState: WCSessionActivationState, error: Error?)`. Why did it use
`throws`? The other APIs, which use NSError in Objective-C, change to
throws in Swift counterpart.

Zhaoxin

On Thu, Sep 8, 2016 at 10:52 AM, Shawn Erickson <shaw...@gmail.com> wrote:

> For one RealmSwift should likely consider changing their enum cases to use
> lowerCamelCase like Swift 3 did. Also at some point it should consider the
> changes to NSError / Swift.Error bridging.
>
> -Shawn
>
> On Wed, Sep 7, 2016 at 7:18 PM Zhao Xin via swift-users <
> swift-users@swift.org> wrote:
>
>> When I use RealmSwift in my project, I got an alert " 'Error' is
>> ambiguous for type lookup in this context".
>>
>> import UIKit
>>
>> import UserNotifications
>>
>> import WatchConnectivity
>>
>> import RealmSwift
>>
>>
>> extension AppDelegate:WCSessionDelegate {
>>
>> func session(_ session: WCSession, activationDidCompleteWith
>> activationState: WCSessionActivationState, error: Error?) {
>>
>>
>> }
>>  }
>>
>>
>> I think the reason is that in Swift, Error is a protocol. And in
>> RealmSwift, there is a `case Error(NSError)` in `public enum
>> RealmCollectionChange`.
>>
>>
>> I managed to eliminate the alert buy change `Error?` to `Swift.Error?`.
>> Are there any other ways to fix this?
>>
>>
>> Zhaoxin
>> ___
>> 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] 'Error' is ambiguous for type lookup in this context

2016-09-07 Thread Zhao Xin via swift-users
When I use RealmSwift in my project, I got an alert " 'Error' is ambiguous
for type lookup in this context".

import UIKit

import UserNotifications

import WatchConnectivity

import RealmSwift


extension AppDelegate:WCSessionDelegate {

func session(_ session: WCSession, activationDidCompleteWith
activationState: WCSessionActivationState, error: Error?) {


}
 }


I think the reason is that in Swift, Error is a protocol. And in
RealmSwift, there is a `case Error(NSError)` in `public enum
RealmCollectionChange`.


I managed to eliminate the alert buy change `Error?` to `Swift.Error?`. Are
there any other ways to fix this?


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


Re: [swift-users] Pass Value of Variable to a Function

2016-09-07 Thread Zhao Xin via swift-users
Now I understand your point. But as Jens said, Swift is a static language,
it won't interpret `property` as a variable after `.`(dot). So for Swift
compiler, you just refer to a none-exist property.

Zhaoxin

On Wed, Sep 7, 2016 at 12:39 PM, Michael Sheaver  wrote:

> Hi Zhao,
>
> Many thanks for your response, and I will give this a try. However, I
> think that I might have used a bad example for the bigger question I was
> trying to ask, and for that I am sorry.
>
> The question that I am really trying to address here is: Is there a more
> Swift-y way to, when passing a parameter to a function, we can tell it
> whether:
> a) we intend to pass in the literal string, or
> b) we want to pass the contents of the named variable?
>
> I know that in some languages, if you prepend the passed parameter with a
> '$', as in $propertyName, the receiving function knows to use the
> *contents* of the variable named propertyName (in this case "calendar")
> instead of the literal string "propertyName".
>
> Can we easily do this in Swift? If not, why not? Can we propose a change
> request to implement either a computed property or a method on the Any()
> class that would allow us to tell a called function whether we are passing
> in a literal type or a variable that contains the data to be processed?
>
> Maybe this would violate the type safety for which Swift is thankfully so
> strongly trying to preserve. I don't know, but I would at lest like to
> consider it, for there ARE good business cases for it.
>
> Does this help to clarify the question. I am posing?
>
> Shawn, let me put this into a Swift file and shoot it your way.
>
> Many thanks!
> Michael
>
> On Sep 6, 2016, at 11:21 PM, Zhao Xin  wrote:
>
> I think you messed up with `Locale` and `NSLocale`.
>
> `Locale` is a struct in Swift 3 to replace the legacy `NSLocale`. The
> latter is a class, it has an inner `structure` called `NSLocale.Key`. For
> `Locale`, there is no `NSLocale.Key`. All there keys are instance
> properties in `Locale`. So in your specific case,
>
> let calendar2 =  (currentLocale as NSLocale).object(forKey:
> NSLocale.Key(rawValue:propertyName))
>
> is just almost the same as `let calendar2 = calendar1`.
>
> If you insist on using `NSLocale.Key`, you should use `NSLocale` instead
> of `Locale`.
>
>
> Zhaoxin
>
> On Wed, Sep 7, 2016 at 10:35 AM, Michael Sheaver via swift-users <
> swift-users@swift.org> wrote:
>
>> I am trying to build a table of current locale properties in code, and
>> have encountered issues with trying to pass the value of a variable to a
>> function:
>>
>> let currentLocale = Locale(identifier: "en_US")
>> let calendar1 = currentLocale.calendar  // "gregorian (fixed)"
>> let propertyName = "calendar"let calendar2 = currentLocale.propertyName // 
>> Error: Value of type 'Locale' has no member 'porpertyName'
>>
>> In the last line of code above, the instance of Locale thinks I am
>> passing it "propertyName" rather than the contents of the variable
>> "calendar".
>>
>> Is there any way to pass the value of propertyName ("calendar") to the
>> instance of Locale? I know that in other languages, you can prepend the
>> variable name like '$propertyName', and that tells it to read the value of
>> the variable.
>>
>> I want to keep this pure Swift if possible.
>> I posted this question on StackOverflow, and got the following that does
>> work:
>>
>> let calendar2 =
>> (currentLocale as 
>> NSLocale).object(forKey:NSLocale.Key(rawValue:propertyName))
>>
>> It does seem odd to me that we must do some crazy Objective-C gymnastics
>> to make it work. It  would seem logical to have a computed property on the
>> Any type named, let's say, contentsOf that would return or pass the
>> contents of the variable to the called function. For example, to use the
>> original code sample above, we could use:
>>
>> let calendar2 = currentLocale.propertyName.contentsOf
>>
>> or something similar. Thus currentLocale.propertyName would pass the
>> literal "propertyName", whereas currentLocale.propertyName.contentsOf
>> would pass the contents "calendar".
>>
>> Does anyone else agree that we need this functionality, or am I way out
>> in left field on this? Or is this already possible and I haven't yet
>> figured it out?
>>
>> Sincerest Regards,
>> Michael
>>
>> Michael Sheaver
>> mshea...@me.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


Re: [swift-users] Pass Value of Variable to a Function

2016-09-06 Thread Zhao Xin via swift-users
I think you messed up with `Locale` and `NSLocale`.

`Locale` is a struct in Swift 3 to replace the legacy `NSLocale`. The
latter is a class, it has an inner `structure` called `NSLocale.Key`. For
`Locale`, there is no `NSLocale.Key`. All there keys are instance
properties in `Locale`. So in your specific case,

let calendar2 =  (currentLocale as
NSLocale).object(forKey:NSLocale.Key(rawValue:propertyName))

is just almost the same as `let calendar2 = calendar1`.

If you insist on using `NSLocale.Key`, you should use `NSLocale` instead of
`Locale`.


Zhaoxin

On Wed, Sep 7, 2016 at 10:35 AM, Michael Sheaver via swift-users <
swift-users@swift.org> wrote:

> I am trying to build a table of current locale properties in code, and
> have encountered issues with trying to pass the value of a variable to a
> function:
>
> let currentLocale = Locale(identifier: "en_US")
> let calendar1 = currentLocale.calendar  // "gregorian (fixed)"
> let propertyName = "calendar"let calendar2 = currentLocale.propertyName // 
> Error: Value of type 'Locale' has no member 'porpertyName'
>
> In the last line of code above, the instance of Locale thinks I am passing
> it "propertyName" rather than the contents of the variable "calendar".
>
> Is there any way to pass the value of propertyName ("calendar") to the
> instance of Locale? I know that in other languages, you can prepend the
> variable name like '$propertyName', and that tells it to read the value of
> the variable.
>
> I want to keep this pure Swift if possible.
> I posted this question on StackOverflow, and got the following that does
> work:
>
> let calendar2 =
> (currentLocale as 
> NSLocale).object(forKey:NSLocale.Key(rawValue:propertyName))
>
> It does seem odd to me that we must do some crazy Objective-C gymnastics
> to make it work. It  would seem logical to have a computed property on the
> Any type named, let's say, contentsOf that would return or pass the
> contents of the variable to the called function. For example, to use the
> original code sample above, we could use:
>
> let calendar2 = currentLocale.propertyName.contentsOf
>
> or something similar. Thus currentLocale.propertyName would pass the
> literal "propertyName", whereas currentLocale.propertyName.contentsOf
> would pass the contents "calendar".
>
> Does anyone else agree that we need this functionality, or am I way out in
> left field on this? Or is this already possible and I haven't yet figured
> it out?
>
> Sincerest Regards,
> Michael
>
> Michael Sheaver
> mshea...@me.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


Re: [swift-users] Can we `override var hashValue`?

2016-09-06 Thread Zhao Xin via swift-users
Thanks Lou.

In addition to what Jordan and Dmitri have said, I think part of the
> confusion is that you are assuming hash values are implicitly used in an
> equality check.  They are not.  They are used when your instances are added
> to certain types of collections.


​You are very nice. But I was not assuming hash values were implicitly used
in an equality check. In fact, my problem was solved on the third email of
mine in this thread.

Here is the history of the question and the answer.

1. On the point of "Can we `override var hashValue`", I was and am on the
side of definitely "Yes". And Jordan Rose, was on the side of perhaps, "but
someone should carefully implemented the `hashValue` on base class and
subclasses, so that the rule "if `a==b`, then `a.hashValue==b.hashValue`
wouldn't be violated".

2. At the beginning, I still thought we could `override var hashValue`. But
it violated the rule with comparing between instances from different
subclasses. My explanation was that since the hashValue on the base class
was not violated the rule, the rule was not broken. Also I insisted that
thought it was not documented, the base of equality should be the types of
instances equaled at first.  I knew my point was weak, so I asked in this
thread to see if there was something I missed.

3. I got the reply from Michael Nisi. But I thought his point was alike
Jordan's. I knew I was gotten the point of " the base of equality should be
the types of instances equaled at first" from somewhere. So I looked up.
Turned out I found it in the book "Core Java".

4. The conclusion: The rule should not be violated at any time. My previous
explanation of "since the hashValue on the base class was not violated the
rule, the rule was not broken" was wrong. However, Jordan's point "someone
should carefully implemented the `hashValue` on base class and subclass, so
that the rule "if `a==b`, then `a.hashValue==b.hashValue` wouldn't be
violated. " was also not correct. As there was no way to `override
hashValue` like that.

Here are my points on " Can we `override var hashValue`":

1. We can. But we should firstly test the `type(of:lhs) == type(of:rhs)`.
If that doesn't equal, we return false. This technique solved the problem
of mine in this thread. This should be the first choice of all situations.

2. We can but we may prefer not to. If we choose not to, we must keep that
to all subclasses of the base class. I don't prefer this way, but someone
may like it. I think doing this may gain more problems than it solves. But
again, since it does not violate any documented rules, it could exist.

3. In both 1 and 2, we must also write `==` for each subclasses.

Zhaoxin

On Wed, Sep 7, 2016 at 5:55 AM, Lou Zell  wrote:

> My question is, apple equals banana, but their hashValues (in their own
>> types)  don't. What's wrong here?
>
> ​
> Hi Zhao.  In addition to what Jordan and Dmitri have said, I think part of
> the confusion is that you are assuming hash values are implicitly used in
> an equality check.  They are not.  They are used when your instances are
> added to certain types of collections.
>
> In your first example, where you print out the hash values but then
> compare lhs.name to rhs.name, the names of the two fruits are both
> "common fruit", and the equality test returns true.  Hash never comes into
> play.  You can test for yourself when the hash gets used:
>
> import Foundation
> class Foo: NSObject {
> override var hash: Int {
> print("Computing hash value!")
> return 1
> }
> }
> var f1 = Foo()
> var f2 = Foo()
> f1 == f2  // Doesn't print anything!
> var aSet = Set()
> aSet.insert(f1)  // Prints "Computing has value!"
>
> Lou
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] strange property observer behavior

2016-09-04 Thread Zhao Xin via swift-users
>
> 1) when `didSet` observer will call?


​For me, it is more like Swift developer tries to override some beginner's
flaw.

​2) infinite loop


​If you intended to do things bad, things ​went bad.

3) override property observer


​You mentioned "TSPL(The Swift Programming Language) ​", and it says in it:

“NOTE

The willSet and didSet observers of superclass properties are called when a
property is set in a subclass initializer, after the superclass initializer
has been called. They are not called while a class is setting its own
properties, before the superclass initializer has been called.

For more information about initializer delegation, see Initializer
Delegation for Value Types and Initializer Delegation for Class Types.”

From: Apple Inc. “The Swift Programming Language (Swift 3 Beta)”。 iBooks.
https://itun.es/us/k5SW7.l

You didn't provide a `init()`, but since you properties were already set.
There was a hidden `init()` when you called `Child()`.

Last,

 let base = child as Base
 base.a  = 4 // still output "base didset" and "child didset"

In Swift, as or as! won't change the instance's dynamic type. So it does
nothing. `type(of:base)` is still `Child`.

Zhaoxin



On Sun, Sep 4, 2016 at 6:25 PM, adelzhang via swift-users <
swift-users@swift.org> wrote:

> Hi all
>
> It sounds convenient to monitor change in property's value using property
> observer.
> But TSPL(The Swift Programming Language) talk little about property
> observer. There
> are some questions abouts property observer.
>
> 1) when `didSet` observer will call?
>
> I assume it's fine that changing property's value in `didSet` observer.
>
> class Foo {
> var a: Int = 0 {
> didSet {
> print("didset")
> a = a + 1
> }
> }
> }
>
> let foo = Foo()
> foo.a = 4  // only output "didset" once
>
> Why it don't cause infinite loop?
>
> 2) infinite loop
>
> // this code snippet cause inifinite loop
> class Foo {
> var a: Int = 0 {
> didSet {
> b = a + 1
> }
> }
>
> var b: Int = 1 {
> didSet {
> a = b - 1
> }
> }
> }
>
> let foo = Foo()
> foo.a = 2
>
> 3) override property observer
>
> class Base {
> var a: Int = 0 {
> didSet {
> print("base didset")
> }
> }
> }
>
> class Child : Base {
> override var a : Int {
> didSet {
> print("child didset")
> }
> }
> }
>
> let child = Child()
> child.a = 2 // output "base didset" and "child didset"
> let base = child as Base
> base.a  = 4 // still output "base didset" and "child didset"
>
> Why overriding property observer still call parent's `didSet` observer?
>
> --
> Adel
>
>
> ___
> 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] Subtract a set of a subclass?

2016-09-02 Thread Zhao Xin via swift-users
You are correct. Whether override `hashValue` is basing on the
implementation of `==`. You can't do what you want. You should follow the
required rules. However, if you don't want to get the unexpected result,
you can always use a `convenience init(_ instance:Self)` in `extension` to
convert subclass to  superclass as I did in previous replies.

Zhaoxin

On Sat, Sep 3, 2016 at 10:12 AM, Dmitri Gribenko <griboz...@gmail.com>
wrote:

> On Sat, Sep 3, 2016 at 4:47 AM, Zhao Xin via swift-users
> <swift-users@swift.org> wrote:
> > Hi Jordan,
> >
> > Both you and I were wrong.
> >
> > My wrongness: Your so called principle should be applied here.
> >
> > Your wrongness: If you really want a different hash value, the parent
> > equality function has to be conservative and say that the different types
> > are different.
>
> That's one way you can satisfy the rules, but not the only one.
>
> Think about class clusters.  NSString has many subclasses that store
> strings in different ways (for example, as Latin1 and UTF-16), but any
> subclass instance compares equal to any other subclass instance that
> carries the same character data, and also produces the same hash
> value.
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Subtract a set of a subclass?

2016-09-02 Thread Zhao Xin via swift-users
think A and B are unrelated types, you should be using
>> composition rather than inheritance.
>>
>> If a subclass overrides hashValue, they must be in a position to affect
>> == as well, and it must work no matter which object is on the left-hand
>> side. NSObject does this by having == call the isEqual(_:) method, but you
>> still need to design your class hierarchy and isEqual(_:) methods carefully.
>>
>> Jordan
>>
>>
>> On Sep 1, 2016, at 16:28, Zhao Xin <owe...@gmail.com> wrote:
>>
>> I believe if B inherits A, they are not the same type. So the rule
>> doesn't apply here.
>>
>> Zhaoxin
>>
>> On Fri, Sep 2, 2016 at 7:02 AM, Nick Brook <nrbr...@gmail.com> wrote:
>>
>>> Hi Jordan,
>>>
>>> Thanks for the advice.
>>>
>>> What if a subclass does implement hashValue differently? It seems you
>>> are saying a subclass should never override hashValue? Should Set not
>>> compare elements with == instead of hashValue?
>>>
>>> Thanks
>>> Nick
>>>
>>> M: +44 (0)7986 048 141
>>> W: http://nickbrook.me
>>>
>>> On 1 Sep 2016, at 23:55, Jordan Rose <jordan_r...@apple.com> wrote:
>>>
>>>
>>> On Sep 1, 2016, at 15:44, Zhao Xin via swift-users <
>>> swift-users@swift.org> wrote:
>>>
>>> Hi Nick,
>>>
>>> Glad to help.
>>>
>>> but when using third party classes I don’t know if the hash values are
>>>> comparable
>>>>
>>>
>>> You can create an extension with a convenient init(:), which creates a
>>> new instance of  the super class basing on the instance of the sub class.
>>> That will guarantee the subtraction. Below code works in Xcode 7.3.1 with
>>> Swift 2.2.
>>>
>>> import Foundation
>>>
>>> func ==(lhs: Foo, rhs: Foo) -> Bool {
>>> return lhs.id == rhs.id
>>> }
>>>
>>> class Foo:Hashable {
>>> let id:Int
>>> var hashValue: Int {
>>> return id
>>> }
>>>
>>> required init(_ id:Int) {
>>> self.id = id
>>> }
>>> }
>>>
>>> class Bar:Foo {
>>> override var hashValue: Int {
>>> return id * 5
>>> }
>>> }
>>>
>>> var fooSet:Set = [Foo(10), Foo(9), Foo(8), Foo(7)]
>>> var barSet:Set = [Bar(8), Bar(7), Bar(6), Bar(5)]
>>>
>>> //fooSet.subtract(barSet) // error: cannot invoke 'subtract' with an
>>> argument list of type '(Set)'
>>> fooSet = fooSet.subtract(barSet as Set) // works, but not what we
>>> want
>>> fooSet.forEach { print("\($0.dynamicType), id:\($0.id)") }
>>> /*
>>>  Foo, id:7
>>>  Foo, id:10
>>>  Foo, id:9
>>> */
>>>
>>>
>>> This isn't really a sensible thing to do. The rules for Hashable require
>>> that `a == b` implies `a.hashValue == b.hashValue`, and `a.hashValue !=
>>> b.hashValue` implies `a != b`. If you break these rules you're going to
>>> have problems no matter what static types you're using.
>>>
>>> Upcasting from Set to Set is the most concise way to solve
>>> this problem.
>>>
>>> Jordan
>>>
>>>
>>>
>>
>>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


Re: [swift-users] Can we `override var hashValue`?

2016-09-02 Thread Zhao Xin via swift-users
The key is how to write the `==` function. It should compare the`
dynamicType`(or `type(of:)` in Swift 3.0) if the class is not a final class.

func ==(lhs: Fruit, rhs: Fruit) -> Bool {



print(lhs.hashValue)

print(rhs.hashValue)



return type(of:lhs) == type(of:rhs) && lhs.name == rhs.name

}


func ==(lhs: Apple, rhs: Apple) -> Bool {

return type(of:lhs) == type(of:rhs) && lhs.name == rhs.name && lhs.shape
== rhs.shape

}


func ==(lhs: Banana, rhs: Banana) -> Bool {

return type(of:lhs) == type(of:rhs) && lhs.name == rhs.name && lhs.shape
== rhs.shape

}



class Fruit:Hashable {

let name:String



var hashValue: Int {

return 0

}



init(_ name:String = "common fruit") {

self.name = name

}

}


enum FruitShape:Int {

case small = 1000

case medium = 2000

case big = 3000

}


class Apple:Fruit {

let shape:FruitShape



override var hashValue: Int {

return 5

}



required init(_ name:String = "common fruit", shape:FruitShape = .medium)
{

self.shape = shape

super.init(name)

}

}


class Banana:Fruit {

let shape:FruitShape



override var hashValue: Int {

return 10

}



required init(_ name:String = "common fruit", shape:FruitShape = .medium)
{

self.shape = shape

super.init(name)

}

}


let apple = Apple()

let banana = Banana()


print(apple == banana)

/*

 5

 10

 false

*/


I got the idea from book "Core Java", mine is version 8, the latest is the
version 10. I learnt how to writing Object oriented code from it. I am glad
it is still useful.


Zhaoxin

On Sat, Sep 3, 2016 at 9:14 AM, Zhao Xin <owe...@gmail.com> wrote:

> There is no reason to compare the shape, it is a constant in each of
>
> these types.  (So I am not sure what your point is.)
>
>
> Sorry. The `let shape` should be `var shape`. I just wanted to make the
> subclass to be something more than the super class.
>
> If two values are equal, their hash values should be equal.  As long
>> as your override implementation guarantees this, you can override
>> hashValue.
>
>
> But the question is how? If this must be guaranteed by the subclass, how
> to writing the override? Or it just can't be done?
>
> You should also understand that the ==(Apple, Apple) and ==(Banana,
>> Banana) are not overrides for ==(Fruit, Fruit), and they would not be
>> called through dynamic dispatch when you have, for example, two apples
>> typed as fruits.
>
>
> In fact, in my example code, `apple` and `banana` is instance of `Apple`
> and `Banana`. They are not using `let apple:Fruit = Apple()`. The `==` used
> the *`Fruit` version* as it was the only appropriate one. My big question
> is, since they used the `*Fruit` version*, and the *`Fruit` version of
> `hashValue`* could guarantee the `hashValue` equality, isn't that enough?
>
> Zhaoxin
>
>
> On Sat, Sep 3, 2016 at 7:02 AM, Dmitri Gribenko <griboz...@gmail.com>
> wrote:
>
>> On Sat, Sep 3, 2016 at 1:31 AM, Zhao Xin via swift-users
>> <swift-users@swift.org> wrote:
>> > func ==(lhs: Apple, rhs: Apple) -> Bool {
>> > return lhs.name == rhs.name && lhs.shape == rhs.shape
>> > }
>> >
>> > func ==(lhs: Banana, rhs: Banana) -> Bool {
>> > return lhs.name == rhs.name && lhs.shape == rhs.shape
>> > }
>>
>> There is no reason to compare the shape, it is a constant in each of
>> these types.  (So I am not sure what your point is.)
>>
>> > My question is, apple equals banana, but their hashValues (in their own
>> > types)  don't. What's wrong here? Is that means we shouldn't override
>> > hashValue in subclass in Swift?
>>
>> This means you should not override hashValue in this particular way.
>> If two values are equal, their hash values should be equal.  As long
>> as your override implementation guarantees this, you can override
>> hashValue.
>>
>> You should also understand that the ==(Apple, Apple) and ==(Banana,
>> Banana) are not overrides for ==(Fruit, Fruit), and they would not be
>> called through dynamic dispatch when you have, for example, two apples
>> typed as fruits.
>>
>> Dmitri
>>
>> --
>> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
>> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
>>
>
>
___
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


  1   2   >