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 back1func swapValues<T>(_ a: inout T, _ b: inout T) { // Classic three-step swap through a temporary2 let temp = a3 a = b4 b = temp5}6 7var x = 5, y = 10// & marks inout arguments; T is Int here8swapValues(&x, &y)// Prints x: 10, y: 59print("x: \(x), y: \(y)")10 11var s1 = "Hello", s2 = "World"// Same function, T is String here12swapValues(&s1, &s2)// Prints s1: World, s2: Hello13print("s1: \(s1), s2: \(s2)")Output
x: 10, y: 5 s1: World, s2: Hello
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