Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Exercise - Guard Statements Imagine you want to write a function to calculate the area of a rectangle. However, if you pass a negative number

Exercise - Guard Statements

Imagine you want to write a function to calculate the area of a rectangle. However, if you pass a negative number into the function, you don't want it to calculate a negative area. Create a function called calculateArea that takes two Double parameters, x and y, and returns an optional Double. Write a guard statement at the beginning of the function that verifies each of the parameters is greater than zero and returns nil if not. When the guard has succeeded, calculate the area by multiplying x and y together, then return the area. Call the function once with positive numbers and once with at least one negative number.

Create a function called add that takes two optional integers as parameters and returns an optional integer. You should use one guard statement to unwrap both optional parameters, returning nil in the guard body if one or both of the parameters doesn't have a value. If both parameters can successfully be unwrapped, return their sum. Call the function once with non-nil numbers and once with at least one parameter being nil.

When working with UIKit objects, you will occasionally need to unwrap optionals to handle user input. For example, the text fields initialized below have text properties that are of type String?.

Write a function below the given code called createUser that takes no parameters and returns an optional User object. Write a guard statement at the beginning of the function that unwraps the values of each text field's text property, and returns nil if not all values are successfully unwrapped. After the guard statement, use the unwrapped values to create and return and instance of User.

struct User {

var firstName: String

var lastName: String

var age: String

}

let firstNameTextField = UITextField()

let lastNameTextField = UITextField()

let ageTextField = UITextField()

firstNameTextField.text = "Jonathan"

lastNameTextField.text = "Sanders"

ageTextField.text = "28"

Call the function you made above and capture the return value. Unwrap the User with standard optional binding and print a statement using each of its properties.

Prefered language is "SWIFT"

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Visual C# And Databases

Authors: Philip Conrod, Lou Tylee

16th Edition

1951077083, 978-1951077082

More Books

Students also viewed these Databases questions