Generic Function in Swift

Level 4225 keystrokes

swapValues<T> exchanges two variables of the same type through inout parameters. It is called once with Ints and once with Strings, printing x: 10, y: 5 and s1: World, s2: Hello.

Swift code

// Both parameters share the placeholder type T; inout allows writing back
1func swapValues<T>(_ a: inout T, _ b: inout T) {
// Classic three-step swap through a temporary
2 let temp = a
3 a = b
4 b = temp
5}
6
7var x = 5, y = 10
// & marks inout arguments; T is Int here
8swapValues(&x, &y)
// Prints x: 10, y: 5
9print("x: \(x), y: \(y)")
10
11var s1 = "Hello", s2 = "World"
// Same function, T is String here
12swapValues(&s1, &s2)
// Prints s1: World, s2: Hello
13print("s1: \(s1), s2: \(s2)")

Output

x: 10, y: 5
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.

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

More Swift examples at level 4

← Swift typing practice