我是新來的Swift,並通過我已經看到的答案搜索了一些,但我試圖找出如何糾正這個問題。我有一個Swift遊樂場,其代碼運行良好,並不返回此錯誤,但在iOS項目中有類似的代碼,它返回此錯誤。當我將纖維計數值與5.5進行比較時發生。二元運算符'<'不能應用於'Double?'類型的操作數。和'雙'
我可以看到兩種情況之間唯一的區別是操場代碼沒有使用來自文本字段的用戶輸入,我將文本轉換爲Double。我輸入一個纖維計數值,並且全部看起來都沒問題。
但是,在iOS項目中,我收到了上面的錯誤消息,並且不明白如何解決它,最重要的是,爲什麼我在一個代碼集中出現錯誤,而不是其他錯誤。看來我要麼讓它在兩種情況下工作,要麼根本不工作。提前致謝。
此代碼運行OK:
var ECA: Double
var FibersCounted: Double
var FieldsCounted: Double
var FieldArea: Double
var SampleVolume: Double
var ResultNumerator: Double
var ResultDenominator: Double
var SampleResult: Double
var SampleLimitofDetection: Double
ECA = 385
FibersCounted = 65
FieldsCounted = 100
FieldArea = 0.00785
SampleVolume = 1200
if FibersCounted <= 5.5 {
ResultNumerator = (ECA * (5.5/100))
ResultDenominator = (FieldArea * SampleVolume * 1000)
SampleResult = ResultNumerator/ResultDenominator
} else {
ResultNumerator = (ECA * (FibersCounted/FieldsCounted))
ResultDenominator = (FieldArea * SampleVolume * 1000)
SampleResult = ResultNumerator/ResultDenominator
}
此代碼返回時fibersCounted相比5.5(即, 「如果fibersCounted < 5.5 {」 線觸發錯誤的錯誤消息:
@IBOutlet weak var sampleVolumeTextField: UITextField!
@IBOutlet weak var numberFibersCountedTextField: UITextField!
@IBOutlet weak var numberBlankFibersCountedTextField: UITextField!
@IBOutlet weak var numberFieldsCountedTextField: UITextField!
@IBOutlet weak var fiberDensityLabel: UILabel!
@IBOutlet weak var limitOfDetectionLabel: UILabel!
@IBOutlet weak var sampleResultLabel: UILabel!
@IBAction func calculatePressed(_ sender: Any) {
let sampleVolume = Double(sampleVolumeTextField.text!)
let fibersCounted = Double(numberFibersCountedTextField.text!)
let numberBlankFibersCounted = Double(numberBlankFibersCountedTextField.text!)
let fieldsCounted = Double(numberFieldsCountedTextField.text!)
var resultNumerator: Double
var resultDenominator: Double
var sampleResult: Double
var sampleLimitofDetection: Double
//calculate sample result based on actual fiber count or 5.5 fiber LOD value
if fibersCounted < 5.5 {
resultNumerator = (385 * (5.5/100))
resultDenominator = (7.85 * sampleVolume!)
let sampleResult = resultNumerator/resultDenominator
} else {
resultNumerator = (385 * (fibersCounted!/fieldsCounted!))
resultDenominator = (7.85 * sampleVolume!)
let sampleResult = resultNumerator/resultDenominator
}
嘿大家,非常感謝你花時間閱讀和回覆建議。我要看看每個答案,然後看看有什麼作用。我會回來讓你們都知道。再次感謝所有的幫助! –
好的 - 所以我能夠使用「如果讓......」來讓它工作。再次感謝所有人的幫助。我也將努力改進包裝/解包語法。感謝所有這些建議。 –