Swifter
Swifter

Reputation: 55

Conditional Statements in Swift

I'm building a simple app in swift that calculates the area of a space. I'm having an issue with the Conditional Statement that will return a message if the user does not enter a width or a height in the text box.

//
//  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.
    }
}

Upvotes: 1

Views: 246

Answers (3)

Beslan Tularov
Beslan Tularov

Reputation: 3131

You can declare and implement your own custom operators in addition to the standard operators provided by Swift. it is more convenient code using Custom Operators

for exemple!!

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"
}

Upvotes: 0

Hayley Guillou
Hayley Guillou

Reputation: 3973

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

or

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

Upvotes: 0

Antonio
Antonio

Reputation: 72820

This statement is incorrect:

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

you have to explicitly check for not nil individually:

if width != nil && height != nil

There's another error though, which generates a runtime exception:

var areaPressed = width! * height!

if either width or height is nil. You should move that in the if body:

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

The reason is that the forced unwrapping operator ! requires that the optional variable it is applied to contains a non-nil value - unwrapping a nil results in a runtime exception.

Upvotes: 2

Related Questions