我的应用程序崩溃,因为在解包值“ header ”时发现 nil 我尝试使用guard let 语句,尽管它不起作用,安全解包该值的最佳方法是什么?
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
self.headerOpen = true
if self.headerOpen == true {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as! HomePageHeader
header.currentUser = self.currentUser
header.usersLocation = self.usersLocation
header.delegate = self
reloadInputViews()
} else if headerOpen == false {
print("header open is false")
}
return header!
}
最佳答案
if let ...
或 guard let ...
可以帮助您。例如:
if let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as? HomePageHeader {
print("header unwrapped")
}
或
guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as? HomePageHeader else { print("header not unwrapped") }
print("header unwrapped")
关于swift - 如何安全地解开 header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49474899/