Return multiple values from a function in Swift


In Swift, you can return multiple values from a function using a tuple. In this article, you will see different examples of how to use a tuple to return multiple values from a function. Here are some more practical examples of functions that return multiple values using tuples in Swift −

Example 1 - Parsing a URL into its Components

import Foundation
func parseURL(urlString: String) -> (scheme: String, host: String, path: String) {
   guard let url = URL(string: urlString) else {
      fatalError("Invalid URL")
   }
   return (url.scheme ?? "", url.host ?? "", url.path)
}
let components = parseURL(urlString: "https://www.example.com/path/to/resource")
print("Scheme:", components.scheme)
print("Host:", components.host)
print("Path:", components.path)

Output

Scheme: https
Host: www.example.com
Path: /path/to/resource

In this example, the parseURL function takes a string representing a URL and returns a tuple with the URL's scheme, host, and path components. If the URL is invalid, the function raises a fatal error.

Example 2 - Splitting a String into Words and Counting Their Occurrences

import Foundation
func countWords(text: String) -> (words: [String], counts: [String: Int]) {
   let words = text.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted)
   var counts = [String: Int]()
   for word in words {
      if !word.isEmpty {
         counts[word, default: 0] += 1
      }
   }
   return (words, counts)
}
let text = "Hello, world! This is a test of word counting."
let result = countWords(text: text)
print("Words: \(result.words)")
print("Words count: \(result.counts)")

Output

Words: ["hello", "", "world", "", "this", "is", "a", "test", "of", "word", "counting", ""]
Words count: ["hello": 1, "counting": 1, "a": 1, "is": 1, "test": 1, "this": 1, "world": 1, "of": 1, "word": 1]

In this example, the countWords function takes a string of text, splits it into individual words, and counts the occurrences of each word. It returns a tuple with two values: an array of words and a dictionary mapping each word to its count. Note that we convert all words to lowercase for case-insensitive counting.

Example 3 - Finding the Maximum and Minimum Values in an Array

import Foundation
func findMinMax(numbers: [Int]) -> (min: Int, max: Int)? {
   guard !numbers.isEmpty else {
      return nil
   }
   var min = numbers[0]
   var max = numbers[0]
   for number in numbers {
      if number < min {
         min = number
      }
      if number > max {
         max = number
      }
   }
   return (min, max)
}
let inputArray = [3, 5, 2, 7, 1, 8]
if let result = findMinMax(numbers: inputArray) {
   print("Array: \(inputArray)")
   print("Min value: \(result.min)")
   print("Max value: \(result.max)")
}

Output

Array: [3, 5, 2, 7, 1, 8]
Min value: 1
Max value: 8

In this example, the findMinMax function takes an array of integers and returns a tuple with the minimum and maximum values in the array. If the array is empty, the function returns nil. We use optional binding (if let result = ...) to handle the case where the function returns nil.

Example 4 - Calculating Statistics

import Foundation
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
   var min = scores[0]
   var max = scores[0]
   var sum = 0
   for score in scores {
      if score > max {
         max = score
      } else if score < min {
         min = score
      }
      sum += score
   }
   return (min, max, sum)
}
let inputArray = [5, 3, 100, 2, 10]
let statistics = calculateStatistics(scores: inputArray)
print("Input array: \(inputArray)")
print("Min value: \(statistics.min)")
print("Max value: \(statistics.max)")
print("Sum value: \(statistics.sum)")

Output

Input array: [5, 3, 100, 2, 10]
Min value: 2
Max value: 100
Sum value: 120

In this example, the calculateStatistics function takes an array of integers as input and returns a tuple with three values: the minimum score, the maximum score, and the sum of all scores. To return the tuple, we simply use the syntax (value1, value2, value3) and separate each value with a comma.

You can then access each value in the tuple using the dot syntax with the corresponding property names (in this example, statistics.min, statistics.max, and statistics.sum).

Conclusion

In conclusion, a tuple is a straightforward Swift data structure that enables you to combine many values into a single compound value. Tuples can be used to send many values as a single parameter to a function or to return multiple values from a function.

Tuple members can be named for faster access, and they can contain any kind of value, including other tuples. Tuples may help your code be clearer and easier to comprehend while providing a simple method to interact with tiny, connected chunks of data.

Updated on: 04-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements