在Swift中if语句/ Obj-C闭包中的非Bool

时间:2016-11-10 19:01:47

标签: objective-c swift

我一直在尝试将教程https://github.com/fastred/CustomScrollView从Objective-C转换为Swift,但我被困在几个地方。

在Objective-C中,它具有以下属性:

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

然后它有if语句:

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

由于这些显然不是Bool,这在Swift中意味着什么?

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

这个似乎是一个封闭,我尝试使用以下方法将其转换为Swift:

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;
};

但转换后的应用程序根本不像原版。有人能告诉我如何将其转换为Swift吗?

1 个答案:

答案 0 :(得分:0)

如果我正确地解释了所有这些,我就会在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
    }
}