Swift:强制转换参数?

时间:2014-06-29 20:00:48

标签: parameters casting closures swift

以下代码导致编译器错误:Could not find member 'Left'

let indexOfConstraint = constraints.indexOfObjectPassingTest { (constraint, idx, stop) in
    return constraint.firstAttribute == .Left
}

NSLayoutAttribute之前预先.Left修复了错误,但有没有办法将constraint投射到NSLayoutConstraint

例如,在Objective-C中,我可以在指定参数时强制转换constraint

NSUInteger indexOfConstraint = [constraints indexOfObjectPassingTest:^BOOL(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
    return constraint.firstAttribute == NSLayoutAttributeLeft
}];

1 个答案:

答案 0 :(得分:6)

您可以使用括号进行投射:

let indexOfConstraint = constraints.indexOfObjectPassingTest { (constraint, idx, stop) in
    return (constraint as NSLayoutConstraint).firstAttribute == .Left
}

......这可能比使用NSLayoutAttribute.Left

更丑陋