Generic Function in Swift

Level 4222 keystrokes

swapValues<T> swaps two variables of any type through inout parameters. The same function swaps two Ints and two Strings, printing x=20, y=10 and s1=World, s2=Hello.

Swift code

// T is a type placeholder; inout lets the function change the caller's variables
1func swapValues<T>(_ a: inout T, _ b: inout T) {
// Keeps a's value, then swaps through the temporary copy
2 let temp = a
3 a = b
4 b = temp
5}
6
// Two Int variables declared on one line
7var x = 10, y = 20
// & passes the variables as inout; T is inferred as Int
8swapValues(&x, &y)
// Prints x=20, y=10
9print("x=\(x), y=\(y)")
10
11var s1 = "Hello", s2 = "World"
// The same function with T inferred as String
12swapValues(&s1, &s2)
// Prints s1=World, s2=Hello
13print("s1=\(s1), s2=\(s2)")

Output

x=20, y=10
s1=World, s2=Hello
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • =× 11
  • (× 9
  • )× 9
  • "× 8
  • ,× 7
  • \× 4
  • &× 4
  • _× 2
  • :× 2
  • {× 1

More Swift examples at level 4

← Swift typing practice