代码之家  ›  专栏  ›  技术社区  ›  j-s

可选类型“float?”的值未展开;是否要使用“!”或者“?”?

  •  0
  • j-s  · 技术社区  · 6 年前

    我用swift定义一个类,如下所示:

    var moduleName : String?
    var moduleWeight : Float = 0
    var moduleMark : Double = 0.0
    var moduleCompletion : Int = 0
    var moduleNotes : String?
    

    我还有一个函数可以访问这些变量

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //
    
        if segue.identifier == "courseWorkTopView"
        {
            if let topViewController = segue.destination as? assignmentTopViewController{
                topViewController.moduleName = detailItem?.moduleName
                topViewController.moduleWeight = detailItem?.value
            }
        }
    }
    

    我得到错误:

    可选类型“float?”的值未展开;是否要使用“!”或者“?”?

    我也试过以下代码

    topViewController.moduleWeight = (detailItem?.value)!
    

    但我得到一个运行时错误:

    线程1:exc_bad_指令(code=exc_i386_invop,subcode=0x0)

    我对斯威夫特不熟悉,如果有人能帮我解决这个问题,那就太好了。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Abdelahad Darwish    6 年前

    你可以这样解决

    topViewController.moduleWeight = detailItem?.value ?? 0
    

    或者改变 模块灯组件 optional

    var moduleWeight : Float?
    

    正常使用

    topViewController.moduleWeight = detailItem?.value
    
        2
  •  1
  •   Gereon    6 年前

    detailItem 为零。如果你想避免撞车,你可以用

    topViewController.moduleWeight = detailItem?.value ?? 0
    

    (或使用任何其他合理的违约行为),或

     if let topViewController = segue.destination as? assignmentTopViewController, let detail = detailItem {
        topViewController.moduleName = detail.moduleName
        topViewController.moduleWeight = detail.value
     }