Swift3 中的 NSPredicate
NSPredicate in Swift3
我正在尝试改变这个:
return [self.allAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *layoutAttributes, NSDictionary *bindings) {
return CGRectIntersectsRect(rect, layoutAttributes.frame);
}]];
转换成可以在 swift3 中运行的东西。到目前为止我试过这个:
return self.allAttributes?.filtered(using: NSPredicate(block: { (layoutAttributes, bindings) -> Bool in
return rect.intersects(layoutAttributes.frame)
})) as! [UICollectionViewLayoutAttributes]?
当然我得到了Value of type 'Any?' has no member 'frame'
我整天都在搜索,但找不到解决方案。
假设您的 allAttributes
声明为 NSArray
。
那么无论如何,你需要一些转换,所以你可以这样写:
return self.allAttributes?.filtered(using: NSPredicate(block: { (layoutAttributes, bindings) -> Bool in
guard let layoutAttributes = layoutAttributes as? UICollectionViewLayoutAttributes else {
print("some thing is wrong...")
return false
}
return rect.intersects(layoutAttributes.frame)
})) as! [UICollectionViewLayoutAttributes]?
但是如果你只包含UICollectionViewLayoutAttributes
,你为什么不把它声明为Swift数组,[UICollectionViewLayoutAttributes]
?
var allAttributes: [UICollectionViewLayoutAttributes] = []
//...
return allAttributes.filter {rect.intersects([=11=].frame)}
您可能需要根据此更改进行一些修复,但通常此类修复会使您的代码更加简单和可读。
我正在尝试改变这个:
return [self.allAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *layoutAttributes, NSDictionary *bindings) {
return CGRectIntersectsRect(rect, layoutAttributes.frame);
}]];
转换成可以在 swift3 中运行的东西。到目前为止我试过这个:
return self.allAttributes?.filtered(using: NSPredicate(block: { (layoutAttributes, bindings) -> Bool in
return rect.intersects(layoutAttributes.frame)
})) as! [UICollectionViewLayoutAttributes]?
当然我得到了Value of type 'Any?' has no member 'frame'
我整天都在搜索,但找不到解决方案。
假设您的 allAttributes
声明为 NSArray
。
那么无论如何,你需要一些转换,所以你可以这样写:
return self.allAttributes?.filtered(using: NSPredicate(block: { (layoutAttributes, bindings) -> Bool in
guard let layoutAttributes = layoutAttributes as? UICollectionViewLayoutAttributes else {
print("some thing is wrong...")
return false
}
return rect.intersects(layoutAttributes.frame)
})) as! [UICollectionViewLayoutAttributes]?
但是如果你只包含UICollectionViewLayoutAttributes
,你为什么不把它声明为Swift数组,[UICollectionViewLayoutAttributes]
?
var allAttributes: [UICollectionViewLayoutAttributes] = []
//...
return allAttributes.filter {rect.intersects([=11=].frame)}
您可能需要根据此更改进行一些修复,但通常此类修复会使您的代码更加简单和可读。