在尝试覆盖toInt()时,在展开Optional值时意外发现nil

时间:2014-12-02 09:45:11

标签: swift

我是Swift的新手,我正在尝试构建一个简单的程序来转换以天,分和秒为单位的周数,但我无法将String转换为Int。当我以为使用toInt()完成时,会在此行中显示一条消息:

var tempoEmDias:Int! = timeInDays.text.toInt()

fatal error: unexpectedly found nil while unwrapping an Optional value...

有人可以帮助我吗?代码如下......

import UIKit

class ViewController: UIViewController {

@IBOutlet var timeInDays: UITextField!

@IBOutlet var numberOfWeeks: UILabel!


@IBOutlet var numberOfHours: UILabel!


@IBOutlet var numberOfMinutes: UILabel!


@IBOutlet var numberOfSeconds: UILabel!


@IBAction func calculaTempo(sender: AnyObject) {

  // BELOW: fatal error: unexpectedly found nil while unwrapping an Optional value. 
    var tempoEmDias:Int! = timeInDays.text.toInt()



    // calcula semana

    var numeroDeSemanas:Int = 0


    if tempoEmDias! <= 7 {
        numeroDeSemanas = 1
    } else {

    numeroDeSemanas = tempoEmDias! / 7

    }

    let numeroDeSemanasCerto:Int = Int(numeroDeSemanas)

    numberOfWeeks.text = "/(numeroDeSemanasCerto) semanas"

    // calcula horas

    let numeroDeHoras = numeroDeSemanasCerto * 24
    numberOfHours.text = "/(numeroDeHoras) horas"

    // calcula minutos

    let numeroDeMinutos = numeroDeHoras * 60
    numberOfMinutes.text = "/(numeroDeMinutos) minutos"

    // calcula segundos

    let numeroDeSegundos = numeroDeMinutos * 60
    numberOfSeconds.text = "/(numeroDeSegundos) segundos"

}

1 个答案:

答案 0 :(得分:3)

您收到此错误,因为toInt()返回一个可选的整数值,您尝试将其分配给非可选的tempoEmDias

来自documentation

toInt()

Use this method to convert a string to an integer value.
The method returns an optional integer value (Int?)—if the conversion succeeds,
the value is the resulting integer; if the conversion fails, the value is nil:

let string = "42"
if let number = string.toInt() {
    println("Got the number: \(number)")
} else {
    println("Couldn't convert to a number")
}
// prints "Got the number: 42"