【问题标题】:Swift: cast closure parameters?Swift:强制转换闭包参数?
【发布时间】:2014-06-29 20:00:48
【问题描述】:

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

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

.Left 之前添加NSLayoutAttribute 可以修复错误,但是有没有办法将constraint 转换为NSLayoutConstraint

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

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

【问题讨论】:

  • 你试过(constraint as NSLayoutConstraint).firstAttribute吗?
  • 是的,我想这是最好的选择。问了这个问题后,我意识到这很有效。

标签: parameters casting closures swift


【解决方案1】:

你可以使用括号来强制转换:

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

...这可以说比只使用NSLayoutAttribute.Left更难看

【讨论】:

  • 是的,我想我会坚持使用后者。谢谢! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多