Swift Practice Exercises: Essential Techniques for Mastering the Framework

Here’s a short practice exercise for Swift programming:

Exercise: Calculate the average of an array

Create a function in Swift that takes an array of numbers as input and returns the average of those numbers.

Here’s an example input:

swiftCopy codelet numbers = [1, 2, 3, 4, 5]

And here’s the expected output:

swiftCopy code3

To complete this exercise, follow these steps:

  1. Create a new Swift file and define a function called calculateAverage.
  2. The function should take an array of integers as an argument.
  3. Calculate the sum of the numbers in the array.
  4. Divide the sum by the number of elements in the array to get the average.
  5. Return the average as a Double.

Here’s an example implementation of the calculateAverage function:

swiftCopy codefunc calculateAverage(_ numbers: [Int]) -> Double {
    let sum = numbers.reduce(0, +)
    let count = Double(numbers.count)
    let average = sum / count
    return average
}

This implementation uses the reduce function to calculate the sum of the numbers in the array, and then divides by the number of elements in the array to get the average.

You can call the function with the example input above to check if it works as expected:

swiftCopy codelet numbers = [1, 2, 3, 4, 5]
let average = calculateAverage(numbers)
print(average) // Output: 3.0

This practice exercise should help you get more comfortable with Swift syntax and programming concepts.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *