ios - 无法修复错误 : unexpectedly found nil while unwrapping an Optional value

标签 ios swift

我无法解决这个问题。当它尝试将answerCorrightly分配给numberLabel时,我收到运行时错误。 :(

var answeredCorrectly: Int? = 0
func endGame(){
    let lastViewLet = LastView()
    println("Count of correct answers: \(answeredCorrectly)")
    lastViewLet.numberLabel.text = String(stringInterpolationSegment: answeredCorrectly)
    answeredCorrectly = 0
    performSegueWithIdentifier("toEnd", sender: nil)
}

LastView 类:

import Foundation
import UIKit



class LastView: ViewController {

    @IBOutlet weak var numberLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        numberLabel.text = "1"
    }


}

最佳答案

您的 answeredCorrectly var 被赋予了一种可选 int 类型,但您为其分配了 0 值。你确定这就是你想要的吗?如果它始终有一个值,您可以使用 Int

如果您使用可选值,则应使用 if let 构造来确保您有一个值:

if let answeredCorrectlyInt = answeredCorrectly as? Int {
    println("Count of correct answers: \(answeredCorrectlyInt)")
    lastViewLet.numberLabel.text = String(answeredCorrectlyInt)
}

此外,当您可以仅使用 String(answeredCorrectly) 并且它会做正确的事情时,您正在使用 String(stringInterpolationSegment:answeredCorrectly)

关于ios - 无法修复错误 : unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31059081/

相关文章:

iphone ipad Nib 返回相同的 self.view.frame.size.width 问题

android - react 原生 : Is it possible to have a Navigator inside a View?

ios - SWIFT:填写 HTML 输入 [类型 =“text”]

ios - Xcode 8.21 (8C1002) 在 VirtualBox 上处理 iPhone 6s 10.1.1 (14B100) 的符号文件时卡住

ios - AVAudioplayer 不播放

ios - CoreML 模型 : Convert imageType model input to multiArray

swift - 将 NavigationBarController 设置为 rootViewController

ios - Swift 3 将两种颜色放在同一个 UIView 中

ios - 检查 AppDelegate 中 session 中的用户,如果没有则触发 UIViewController

ios - iOS 的 Apache Tika 替代品