2014-12-19 115 views
1

我在swift中構建了一個計算空間區域的簡單應用程序。如果用戶未在文本框中輸入寬度或高度,則條件語句會出現問題,並返回一條消息。Swift中的條件語句

// 
// ViewController.swift 
// areaCalculator 
// 
// 
// Copyright (c) 2014 Dandre Ealy. All rights reserved. 
// 

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var widthTxt: UITextField! 
    @IBOutlet weak var heightTxt: UITextField! 

    @IBOutlet weak var area: UILabel! 

    @IBAction func buttonPressed(sender: AnyObject) { 

     var width = widthTxt.text.toInt() 
     var height = heightTxt.text.toInt() 

     var areaPressed = width! * height! 

     if ((width) && (height) != nil){ 
      area.text = "The area is \(areaPressed)" 
     } else { 
      area.text = "Enter the width and the height" 
     } 
    } 
    override func viewDidLoad() { 
     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. 
    } 
} 
+0

你有什麼問題?從您的問題中不清楚 – jrturton

+0

我收到&&邏輯運算符的錯誤,它表示「可選類型'$ T6'不能用作布爾值;測試'!= nil'而不是 – Swifter

回答

2

這種說法是不正確:

if ((width) && (height) != nil) 

你必須明確地檢查不無單獨:

if width != nil && height != nil 

還有一個錯誤,雖然,這產生一個運行時異常:

var areaPressed = width! * height! 

如果任widthheight爲零。您應該移動,在if體:

if width != nil && height != nil { 
    var areaPressed = width! * height! 
    area.text = "The area is \(areaPressed)" 
} else { 
    area.text = "Enter the width and the height" 
} 

的原因是被迫展開操作!需要將其應用到可選變量包含非空值 - 展開運行時異常一比零的結果。

+0

我仍然收到運行時錯誤 – Swifter

+0

@Swifter發生了什麼? – Antonio

0
if (width != nil) && (height != nil){ 
    var areaPressed = width! * height! 
    area.text = "The area is \(areaPressed)"   
} else { 
    area.text = "Enter the width and the height" 
} 

if (width == nil) || (height == nil){ 
    area.text = "Enter the width and the height"   
} else { 
    var areaPressed = width! * height! 
    area.text = "The area is \(areaPressed)" 
} 
+0

我把代碼放入後,我的我在控制檯中得到這個消息 libC++ abi.dylib:以NSException類型的未捕獲異常終止 (lldb) – Swifter

0

除了Swift提供的標準運算符外,您還可以聲明和實現自己的自定義運算符。 這是更方便的代碼使用自定義運算符

爲例!

prefix operator ! {} 
prefix func ! (a: Int) -> Bool { 
    return a != 0 
} 

if !width && !height { 
    var areaPressed = width! * height! 
    area.text = "The area is \(areaPressed)" 
} else { 
    area.text = "Enter the width and the height" 
}