Henny Lee Henny Lee - 1 year ago 84
Objective-C Question

Non Bool in if statement / Obj-C closures in Swift

I've been trying to convert the tutorial https://github.com/fastred/CustomScrollView from Objective-C to Swift but I'm stuck in a few places.

In Objective-C it has the properties:

@property (nonatomic, weak) UIDynamicItemBehavior *decelerationBehavior;
@property (nonatomic, weak) UIAttachmentBehavior *springBehavior;


and then it has the if statement:

if self.decelerationBehavior && !self.springBehavior { ... }


Since these are clearly no
Bool
's, what does this mean in Swift?




void(^solveForY)(CGPoint*) = ^(CGPoint *anchor) {
if (deltaY != 0) {
anchor->y = a * anchor->x + b;
}
};


This one seems to be a closure and I've tried converting it to Swift using:

func solveForY(_ anchor: inout CGPoint) { if deltaY != 0 { anchor.y = a * anchor.x + b } }





__weak typeof(self)weakSelf = self;

decelerationBehavior.action = ^{
CGRect bounds = weakSelf.bounds;
bounds.origin = weakSelf.dynamicItem.center;
weakSelf.bounds = bounds;
};





But the converted app doesn't behave like the original at all. Can someone tell me how to convert this to Swift?

Answer Source

If I'm interpreting all that correctly, here's how I would do it in Swift:

var decelerationBehavior: UIDynamicItemBehavior?
var springBehavior: UIAttachmentBehavior?

// the if statement in Objective-C is checking for nil. In Objective-C nil == 0 == false
if let decelerationBehavior = decelerationBehavior, let springBehavior = springBehavior { ... }

let solveForY: (CGPoint) -> () = { (anchor) in
    if deltaY != 0 {
        anchor.y = a * anchor.x + b;
    }
}

decelerationBehavior.action = { [weak self] in
    if let weakSelf = self {
        CGRect bounds = weakSelf.bounds
        bounds.origin = weakSelf.dynamicItem.center
        weakSelf.bounds = bounds
    }
}