I'm making a simple temperature converter for a mobile apps class using Swift. We're sort of breezing over swift so I don't have a lot of experience with it. I had a lot of problems getting it to compile but I eventually got everything all nice and neat, no warning or errors of any sort, and I'm happy with my MVC style code. The only problem is that when I enter a temp and click the Convert button, my log checkpoints prove that I'm getting he correct double value for conversion, and I caste it as a String, but when I try to change the outputText label I get the fatal error: unexpectedly found nil while unwrapping an Optional value. I was hoping it's something very simple that a second pair of eyes could catch. My app looks like this...
My ViewController is...
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
}
}
and my convertModel class (i know, the class should be capitalized, by the time I noticed and tried to change it, it broke everything) is...
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)
}
}
}
Any help is greatly appreciated. But please bear in mind that this is very Swift 101, so any overly complicated solutions don't help greatly. Thanks.