Re: Referring to self in property initializer
Re: Referring to self in property initializer
- Subject: Re: Referring to self in property initializer
- From: Rick Mann <email@hidden>
- Date: Fri, 14 Aug 2015 16:24:06 -0700
> On Aug 14, 2015, at 16:07 , Jens Alfke <email@hidden> wrote:
>
>
>> On Aug 14, 2015, at 3:44 PM, Rick Mann <email@hidden> wrote:
>>
>> What is the type of "self" in the initializer closure,
>
> Wow, I didn’t even think you could use ‘self’ in such a context, since you’re not inside a method, just a closure. But it looks as though ‘self’ has type 'MyDelegate -> () -> MyDelegate’, according to the error message you got. I can’t remember the associativity of ‘->’; it seems something like a function that takes a MyDelegate and returns a function that returns a MyDelegate? Weird.
>
>> and is there a way to refer to the enclosing class instance? I also had trouble locating this in the Swift 2 guide, if it's there at all.
>
> No, I don’t think you can access the instance that the variable is going to be assigned to.
I really would've hoped that since the closure is defined within the scope of an instance of the class, that it would have a self made available to it. I've seen similar code that used "[unowned self] in" to use a weak reference. Just like a closure inside a func can reference self, I think this should be treated as a closure "inside" the var.
>> I can do it with a separate member function and call that in the initializer, but that introduces a lot of boilerplate, as well as creating a method I don't intend to ever be called separately.
>
> Why wouldn’t you just move the body of that closure into your init method? Something like
>
> func init() {
> let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("myident")
> backgroundSession = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
> }
Well, that makes sense, except I actually want to make that variable lazy.
> (And looking at the code more closely, are you really sure you want to create an NSURLSession for every instance of MyDelegate? Usually NSURLSession is a singleton, or at most you’d have a handful of them.)
In this case, MyDelegate is a singleton, and a variant of the design has a few of them that really do want separate sessions.
--
Rick Mann
email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden