我正在使用Swift爲移動應用程序類製作簡單的溫度轉換器。 我們很快就有了這種快感,所以我沒有太多的經驗。編譯時遇到了很多問題,但我最終得到的所有內容都很好,沒有任何警告或錯誤,而且我對MVC樣式代碼感到滿意。唯一的問題是,當我輸入一個temp並單擊Convert按鈕時,我的日誌檢查點證明我正在爲轉換修改雙精度值,並將它作爲字符串進行分類,但是當我嘗試更改outputText標籤時,得到致命錯誤:意外地發現零,同時展開一個可選值。我希望能夠捕捉到第二雙眼睛,這很簡單。 我的應用程序看起來像這樣...致命錯誤:在嘗試更改UILabel文本時展開可選值時出現nil意外發現
我的ViewController是...
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,所以任何過於複雜的解決方案都沒有太大的幫助。謝謝。
你是否連接故事板的插座?你有沒有檢查你的方法/文本字段不返回零? –
我的第一個猜測是你的按鈕沒有連接起來。有兩種常用的方法可以測試代碼是否按預期工作:斷點和打印語句。只需將一些打印語句添加到代碼中,並查看它們何時停止發生。我會建議你的第一個打印()在你的功能的開始,這是一個按鈕上按 – Tyrelidrel
顯然它沒有正確連接。我放了一些打印語句,並且在viewDidLoad上看到了一個,但是當我單擊按鈕時沒有任何打印語句。事實之後有沒有辦法連接它們?我試圖創建另一個按鈕,連接我學習的方法,並且click方法中唯一的一個是print語句,它沒有錯誤消息而崩潰了應用程序,只是顯示了print語句行,並說線程1:斷點3.1 –