0

getting error while upgrading from swift 3 to swift 4. the error comes when using UICollection performBatchUpdates() method. My code looks something like this,

Class A: UICollectionViewDelegate {
    @IBOutlet weak var collectionView: UICollectionView!

    func someMethod() {
         collectionView?.performBatchUpdates({ [weak self] _ in // error:  Expression type '(_) -> _' is ambiguous without more context
             self?.collectionView?.deleteItems(at: [IndexPath(item: 0, section: 0)])
            }, completion: nil)
         })
    }
} 

3 Answers3

1

_ in means:

  1. Acknowledging the existence of a variable being passed to you in to the closure.
  2. Yet you want to ignore that variable ie not allocate any memory. You ignore it by not giving the variable a name. See What's the _ underscore representative of in Swift References?.

If a variable is not being passed from performBatchUpdates then that acknowledgement becomes unnecessary and incorrect. So you have to remove _. But still keep in because you need to pass in a weak reference to self to avoid memory issues.

mfaani
  • 33,269
  • 19
  • 164
  • 293
0

remove "_" in

//...
collectionView?.performBatchUpdates({ [weak self] _ in
//...

make it

//...
collectionView?.performBatchUpdates({ [weak self] in
//...
Durdu
  • 4,649
  • 2
  • 27
  • 47
0

Your whole code won't compile as class should has a NSObject descendant in addition that performBatchUpdates has no variables in it's completion so this _ should be removed

class A : UIViewController,UICollectionViewDelegate {

        @IBOutlet weak var collectionView: UICollectionView!

        func someMethod() {
            collectionView?.performBatchUpdates({ [weak self]  in
                self?.collectionView?.deleteItems(at: [IndexPath(item: 0, section: 0)])
          })
        }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87