In this workshop you will learn about user-defined functions that return a value to its caller.

Before you begin, I assume you have done the following:

workshop25-fig00 workshop25-finder
Figure A: The Xcode project zip file Figure B: Finder view of the Xcode project

Functions That Return A Value

If you want a function to return one or more values to its caller, you’ll have to create a user-define function. Such a function has this syntax.

The function’s arguments are optional; however it must return a value to its caller. After the arrow ->, you add the function’s return type. It could be any one of Swift’s standard type (String, Char, Double Float, Int, Bool) or a collection type (Array, Dictionary)

Using a Function To Calculate Final Grade

Suppose an English teacher asked you to create an iOS application that calculates her students’ final grades. The app should prompt the teacher for a student’s midterm exam grade and the final exam grade. The final grade is 40 percent of the midterm exam grade plus 60 percent of the final exam grade. The teacher wants the final grade correctly round to the nearest integer. For now, code the application to process one student’s grade. Following is the pseudocode solution for this problem.

Coding The ViewController.swift File

To translate above pseudocode into Swift code, you have to first click the ViewController.swift class file to load it in the code editor, then add code shown below in the calculateGradeButtonTapped() function.

@IBAction func calculateGradeButtonTapped(sender: AnyObject) {
  // Convert each Text Field type to an optional Int
  let midterm: Int? = midtermExamScore.text.toInt()
  let final: Int? = finalExamScore.text.toInt()

  // Ensure the Text Fields aren't nil before unwrapping them with the ! and calling
  // the calculateAndReturnFinalGrade() function
  if midterm != nil && final != nil {
    var finalGrade: Int = calculateAndReturnFinalGrade(midterm!, finalExamScore:final!)

    // Format and display the finalGrade in the label object
    outputLabel.text = NSString(format: "Final grade %i", finalGrade)
  } else {
    // The user entered invalid data in one or both Text Field objects,
    // so display an error message in the label object
    outputLabel.text = "Only numbers are allowed in the text boxes"

Next, add code shown below in the calculateAndReturnFinalGrade() function.

func calculateAndReturnFinalGrade(midtermExamScore:Int, finalExamScore:Int) -> Int {
  let midtermWeight : Float = 0.40
  let finalWeight: Float = 0.60
  let grade: Float = midtermWeight * Float(midtermExamScore) + finalWeight * Float(finalExamScore)
  let roundGrade: Float = grade + 0.50
  return Int(roundGrade)

Test The App In The iOS Simulator

After entering above code in the ViewController.swift file, test the application in the iPad or iPhone Simulator. Here are samples of what the app’s user interface will look like on the iPhone 4 Simulator screen, after entering data in the Text Fields and clicking the Calculate Grade button.

workshop25-fig01 workshop-figh02


No responses yet

Leave a Reply

UIDocument Demystified: A Step-by-step Guide on Local and iCloud Document Storage