UICollectionViewLayout
包含一个函数 prepareForCollectionViewUpdates
func prepareForCollectionViewUpdates(_ updateItems: [AnyObject]!) // updateItems is an array of UICollectionViewUpdateItem
UICollectionViewUpdateItem
包含属性indexPathBeforeUpdate
var indexPathBeforeUpdate: NSIndexPath? { get }
我正在寻找CollectionViewLayout
类的某些代码,该类是UICollectionViewFlowLayout
的子类,XCode需要两个!
S来解开indexPathBeforeUpdate
(这是其Getter返回NSIndexPath?
的属性)。看来这只需要一个!
即可解开。相关代码:
class CollectionViewLayout: UICollectionViewFlowLayout {
var insertIndexPaths = NSMutableArray()
var deleteIndexPaths = NSMutableArray()
override func prepareForCollectionViewUpdates(updateItems: [AnyObject]!) {
super.prepareForCollectionViewUpdates(updateItems)
deleteIndexPaths.removeAllObjects()
insertIndexPaths.removeAllObjects()
for update in updateItems {
if update.updateAction == UICollectionUpdateAction.Delete {
deleteIndexPaths.addObject(update.indexPathBeforeUpdate!!) // <- I have a question here
} else if update.updateAction == UICollectionUpdateAction.Insert {
insertIndexPaths.addObject(update.indexPathAfterUpdate!!)
}
}
...
}
}
如果我只使用一个!unwrap update.indexpathbeforeupdate
deleteIndexPaths.addObject(update.indexPathBeforeUpdate!)
我得到错误:
Value of optional type 'NSINdexPath?' not unwrapped; did you mean to use '!' or '?'?"
我得到了一个修复建议,建议"插入!
,带有两个!'s
拆卸更新。indexPathBeforeUpdate
,代码运行正常。
要调查,我只是在for循环中插入了一些变量:
for update in updateItems {
var myUpdate = update // option-click shows myUpdate is an AnyObject
var indexPath1 = update.indexPathBeforeUpdate // option-click shows indexPath1 is an NSIndexPath?!
var indexPath2 = update.indexPathBeforeUpdate! // option-click shows indexPath2 is an NSIndexPath?
var indexPath3 = update.indexPathBeforeUpdate!! // option-click shows indexPath3 is an NSIndexPath
...
}
在变量上单击选项,显示上面的评论中的类型。
当UICollectionViewUpdateItem
的文档显示indexPathBeforeUpdate
是可选的NSIndexPath
(NSIndexPath?
)时,为什么Xcode需要两个!
S来解开update.indexPathBeforeUpdate
?
请注意,当您在您的for-In Loop属性中提取update
的自动完成时,它可能会返回的是可选的?那是因为您正在使用[AnyObject]
的数组。Swift不能保证该对象将拥有您要的属性,因此将其包装在可选的中。
如果您铸造了该数组,则没有双重包装问题(或者至少您已经将第一力拆开到了演员阵中)。
for update in updateItems as! [UICollectionViewUpdateItem] {
if update.updateAction == UICollectionUpdateAction.Delete {
deleteIndexPaths.addObject(update.indexPathBeforeUpdate!)
} else if update.updateAction == UICollectionUpdateAction.Insert {
insertIndexPaths.addObject(update.indexPathAfterUpdate!)
}
}
我猜想苹果还没有时间审核此API。将来我希望方法签名会更改为:
override func prepareForCollectionViewUpdates(updateItems: [UICollectionViewUpdateItem])
这将使这成为非问题。目前,这只是我们必须处理的。