1

我正在使用 Swift 为移动应用程序类制作一个简单的温度转换器。我们有点轻而易举,所以我没有太多的经验。我在编译它时遇到了很多问题,但最终我得到了一切都很好而且整洁,没有任何警告或错误,而且我对我的 MVC 样式代码感到满意。唯一的问题是,当我输入一个临时值并单击“转换”按钮时,我的日志检查点证明我得到了正确的双精度值进行转换,并且我将其转换为字符串,但是当我尝试更改 outputText 标签时,我得到致命错误:在展开可选值时意外发现 nil。我希望这是一件非常简单的事情,第二双眼睛可以捕捉到。我的应用程序看起来像这样......

应用程序视图

我的视图控制器是...

import UIKit

class ViewController: UIViewController
{

    @IBOutlet weak var tempInput: UITextField!
    @IBOutlet weak var tempOutput: UILabel!
    @IBOutlet weak var convertMethod: UISwitch!

    override func viewDidLoad()
    {
        print("view load confirmed");
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func convert(sender: AnyObject!)
    {
        print ("button press confirmed");

        let t = Double(tempInput.text!)
        let m = convertMethod.on
        let result = convertModel(temp:t!,method:m)
        print("result has been set to object variable created as stated above");

        let afterConvert = result.convertTemp()
        print("the convertTemp method was called and the result was stored as the double: \(afterConvert)");

        let finalForm = String(afterConvert)
        print("converted the double into the string: \(finalForm)");

        tempOutput.text = finalForm
        //^^^^^^^ this is the line that fails
    }
}

而我的 convertModel 类(我知道,该类应该大写,当我注意到并尝试更改它时,它破坏了一切)是......

import Foundation
class convertModel
{
    var temp:Double?
    var method:Bool?

    init(temp:Double,method:Bool)
    {
        self.temp = temp
        self.method = method
        print("object of type convertModel created with \(temp) as temp and \(method) as method");
    }

    func convertTemp()->Double
    {
        print("convertTemp method entered");

        if method == true
        {
            print("if conditional entered");
            print("conversion completed, exiting convertTemp method");

            return (temp! * (9/5) + 32)
        }
        else
        {
            print("else conditional entered");
            print("conversion completed, exiting convertTemp method");
            return (temp! - 32) * (5/9)
        }
    }
}

任何帮助是极大的赞赏。但请记住,这是非常 Swift 101,因此任何过于复杂的解决方案都无济于事。谢谢。

4

1 回答 1

0

所以我不知道为什么或如何 UILabel 失去了它与 ViewController 的初始链接,但在绝望中我做了旧的 Ctrl + Click 拖动到 ViewController 并将生成的 Outlet 命名为其他名称(tempOutputs),重命名文本分配,现在它可以工作了。因此,这与其说是一个答案,不如说是对于任何最终来到这里的人来说都是一种解决方法。

于 2015-11-19T09:07:00.537 回答