2

I want to translate to following objective-c code to Swift:

+ (void)someClassFunction {
   __weak __typeof(self)weakSelf = self;
}

My result would be:

class func someClassFunction() {
   var weakSelf = self
}

The problem is that I cannot apply weak inside a method.

How can I make a weak reference to self in class function in Swift?

Here is the code I want to translate:

__weak __typeof(self)weakSelf = self;
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
    completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer != NULL) {
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            UIImage *croppedImage = [weakSelf cropImage:image withCropSize:cropSize];
            completion(croppedImage);
        }
    }];


+ (UIImage *)cropImage:(UIImage *)image withCropSize:(CGSize)cropSize
{
...
}

Edit:

Do I really need the week reference in Swift or can I just do the following?

ClassName.cropImage(...)
Michael
  • 32,527
  • 49
  • 210
  • 370
  • Why do you need to do it? There usually is other way of breaking retain cycles. – Jakub Vano Mar 19 '15 at 12:26
  • possible duplicate of [How to Correctly handle Weak Self in Swift Blocks with Arguments](http://stackoverflow.com/questions/24468336/how-to-correctly-handle-weak-self-in-swift-blocks-with-arguments) – holex Mar 19 '15 at 12:27
  • @JakubVano I posted some more code. Hope that helps. – Michael Mar 19 '15 at 12:28
  • Usually? It depends on the situation whether you want to store the block in a property of `self` (or of an object that is retained by `self` or an object that is retained by an object that is retained by `self` …) You simply cannot say that in general. – Amin Negm-Awad Mar 19 '15 at 12:28
  • @AminNegm-Awad I was not implying that for each situation there is the same solution. I was just stating, that there are methods of breaking retain cycles other than directly translating provided objc code. – Jakub Vano Mar 19 '15 at 12:42

1 Answers1

-1

You can translate closure as

{[weak self] imageDataSampleBuffer, error in
    // self is weak in this closure
    ...
}
Jakub Vano
  • 3,833
  • 15
  • 29