swift - 如何安全地解开 header 值

标签 swift collections view

我的应用程序崩溃,因为在解包值“ 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/

相关文章:

swift - tvOS:从 Swift 调用 JavaScript 以实现 TVML 应用程序

iOS:在 WebView 中播放嵌入式剪辑时静音

java - 如何比较两个对象列表的对象字段差异?

postgresql - 哪些对象可以通过 DROP VIEW CASCADE 删除

asp.net-mvc - RedirectToAction 根本不起作用

database - cakephp 3 在文本框中预填充用户详细信息

ios - 访问 UITableView 标题 View

ios - swift_dynamiccast 在 iOS 中处理过多并影响性能

java - 如何过滤流映射期间抛出异常的元素

java - Java中的所有列表是否都维护插入顺序