表达式类型'(_)-> _'不明确,没有更多上下文

时间:2019-09-23 12:17:47

标签: ios swift swift4

从swift 3升级到swift 4时出现错误。使用UICollection performBatchUpdates()方法时出现错误。我的代码看起来像这样,

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 个答案:

答案 0 :(得分:1)

_ in的意思是:

  1. 确认存在一个变量,该变量将被传递给闭包中的
  2. 但是您想忽略该变量,即不分配任何内存。您可以通过不给变量命名来忽略它。看到 What's the _ underscore representative of in Swift References?

如果未从performBatchUpdates传递变量,则     确认变得不必要和不正确。因此,您必须删除_。但仍要保留in,因为您需要在 in 中传递对weak的{​​{1}}引用,以避免出现内存问题。

答案 1 :(得分:0)

删除“ _”

export class GithubFollowersService extends DataService {

  constructor(http:Http) {
    super('https://api.github.com/users/IDBRAHIMDEV/followers',http)
   }

做到

  constructor(private url : string ,private http : Http) { }

  getAll(){
    return this.http.get(this.url).
    pipe(
      catchError(
        this.handleError
      )   
    )}

答案 2 :(得分:0)

您的整个代码将无法编译,因为该类应该具有NSObject的后代,此外,performBatchUpdates的补全中没有变量,因此应删除此_

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)])
          })
        }
}