为什么我收到错误 "cannot assign value of type (class) to type UICollectionViewDelegate, UICollectionViewDataSource?"

Why I get error "cannot assign value of type (class) to type UICollectionViewDelegate, UICollectionViewDataSource?"

当我声明我的集合视图时,出现错误 "cannot assign value of type (class) to type UICollectionViewDelegate, UICollectionViewDataSource":

let collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    return collectionView
}()

但是当我添加 "lazy var" 时错误消失了。我不知道为什么?有人可以为我解释一下吗?

lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    return collectionView
}()

闭包在初始化期间被调用,因此您还不能使用 self 访问实例的任何属性或方法。如果您需要访问 self ,则必须将 let 替换为 lazy var.

let collectionView: UICollectionView = {
   let layout = UICollectionViewFlowLayout()
   let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
   collectionView.delegate = self // You cannot use
   collectionView.dataSource = self // You cannot use
   return collectionView 
}()

添加惰性强制iOS 以仅在第一次需要时检查 collectionView 的实例化。因此它不会在编译时给你一个错误。在此之前,它给出了一个错误,因为初始化尚未完成并且您正在设置相同的属性。

   let collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    return collectionView
}()

在自我初始化之前,您无法访问自我。因为到目前为止还没有您的 class 对象。实例方法和变量属于 class 的对象而不属于 class,即它们可以在创建 class 的对象后调用。所以它给你错误。

lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.delegate = self
    collectionView.dataSource = self
    return collectionView
}()

lazy var 表示在初始化时跳过这个变量。如果任何变量标记为惰性,它将在第一次使用之前不会分配。您已将此计算变量标记为惰性。因此,无论何时它将被 class 中的任何函数使用,它总是会分配 class (self) 的对象。