Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift's "if let" equivalent in Objective C

What would be "if let" equivalent in Objective C? The example snippet I want to convert to Objective C is below;

if let pfobjects = images as? [PFObject] {
    if pfobjects.count > 0 {
        var imageView: PFImageView = PFImageView()
        imageView.file = pfobjects[0] as! PFFile
        imageView.loadInBackground()
    }
}
like image 774
Dhyaan Avatar asked Jan 09 '16 04:01

Dhyaan


2 Answers

There's no direct equivalent to if let in Objective-C, because if let does Swift-specific things (unwrapping optionals and rebinding identifiers) that don't have direct equivalents in Objective-C.

Here's a nearly equivalent of your Swift code:

if (images != nil) {
    NSArray<PFObject *> *pfobjects = (id)images;
    if (pfobjects.count > 0) {
        PFImageView *imageView = [[PFImageView alloc] init];
        assert([pfobjects[0] isKindOfClass:[PFFile class]]);
        imageView.file = (PFFile *)pfobjects[0];
        [imageView loadInBackground];
    }
}

But this Objective-C code won't verify that images only contains instances of PFObject, and should successfully create an image view as long as pfobjects[0] is a PFFile. Your Swift code will do nothing (create no image view) if images contains any non-PFObject elements.

like image 157
rob mayoff Avatar answered Oct 24 '22 05:10

rob mayoff


You can use NSPredicate to verify the array contains only instances of PFObject:

NSPredicate *p = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", [PFObject class]];
NSInteger numberThatArePFObjects = [images filteredArrayUsingPredicate:p].count;
if(numberThatArePFObjects && numberThatArePFObjects == images.count){
    // certain that images only contains instances of PFObject.
}

If however you weren't working with an array but a single object then it is simpler:

if([image isKindOfClass:[PFObject class]]){
    // certain that image is a valid PFObject.
}

Or if you wanted a new variable:

PFObject* obj = nil;
if([image isKindOfClass:[PFObject class]] && (obj = image)){
    // certain that obj is a valid PFObject.
}
like image 33
malhal Avatar answered Oct 24 '22 06:10

malhal