Swift - Function Returning Multiple Values

Introduction

Functions are not limited to returning a single value.

In Swift, you can use a tuple type in a function to return multiple values.

The following example shows a function that takes in a string containing numbers, examines each character in the string, and counts the number of odd and even numbers contained in it:

func count(string: String) -> (odd:Int, even:Int)
      var odd = 0
      var even = 0
      for char in string
         let digit = String(char).toInt(
         if (digit != nil)
             (digit!) % 2 == 0 ? even++ : odd+
      }
      return  (odd, even)
}

The (odd:Int, even:Int) return type specifies the members of the tuple that would be returned by the function- odd and even.

To use this function, pass it a string and assign the result to a variable or constant, like this:

var result = count ("123456789")

The return result is stored as a tuple containing two integer members, named odd and even :

Demo

func count(string: String) -> (odd:Int, even:Int)
      var odd = 0, even =
      for char in string
         let digit = String(char).toInt(
         if (digit != nil)
             (digit!) % 2 == 0 ? even++ : odd+
      }//from w  w  w.j  a  v a  2  s  . c o  m
      return  (odd, even)
}

var result = count ("123456789")
print("Odd: \(result.odd)")         //5
print("Even: \(result.even)")       //4

The use of the ! character is known as forced unwrapping of an optional's value.

Related Topic