我是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"

}

最佳答案

出现此错误是因为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"

关于swift - 尝试覆盖toInt()时,在展开Optional值时意外发现nil,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27246239/

10-15 14:11