1

I have a property, that in Objective-C I created like this:

self.myProperty = [[MyClass alloc] initWithCompletionBlock:^(MyClass *object) {
   dispatch_async(dispatch_get_main_queue(), ^{
       [self doSomethingAfterInitialization];
   });
}];

And it worked great. Initialization of the MyClass object could create an indeterminate amount of time, so I passed a completionHandler in to it. When it finished, doSomethingAfterInitalization: would handle business.

Now in Swift, I'm trying to create the same object and assign it to a property, with problems.

The property never will change, so it makes sense to me to create it as a Swift constant.

So I'm trying it like this:

let myProperty = MyClass(completionBlock:{ (MyClass) -> (Void) in dispatch_async(dispatch_get_main_queue(), doSomethingAfterInitialization())})

To me that seemed like a direct translation... but the Swift compiler tells me that's not correct, via the error

Use of instance member 'doSomethingAfterInitialization' on type 'MyViewController'; did you mean to use a value of type 'MyViewController' instead?

Well that didn't help much. So instead I tried changing the call to the doSomethingAfterInitialization function to self. doSomethingAfterInitialization(), in which case I see

Value of type '(NSObject) -> () -> TodayWidgetTableViewController' has no member 'doSomethingAfterInitialization'

Any idea how I can fix this? Obviously my initializer is a little weird in the first place, so I'm wondering if this is something that doesn't really translate at all to Swift.

bpapa
  • 21,409
  • 25
  • 99
  • 147
  • Is the `MyClass` in `completionBlock:{ (MyClass) -> (Void)` what you actually have in your code? That should be the name of the parameter; right now it's a type name, which is probably screwing up the type inference. – jscs Oct 14 '16 at 00:02
  • Oh, you also can't use `self` as part of the initial value of one of your own properties (at least not on a constant). See [Initializing Swift properties that require self as an argument](http://stackoverflow.com/q/25149248) Also related is: [Swift "variable not initialized before use", but it's not used](http://stackoverflow.com/q/31942742) – jscs Oct 14 '16 at 00:19

0 Answers0