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 variables1func swapValues<T>(_ a: inout T, _ b: inout T) { // Keeps a's value, then swaps through the temporary copy2 let temp = a3 a = b4 b = temp5}6 // Two Int variables declared on one line7var x = 10, y = 20// & passes the variables as inout; T is inferred as Int8swapValues(&x, &y)// Prints x=20, y=109print("x=\(x), y=\(y)")10 11var s1 = "Hello", s2 = "World"// The same function with T inferred as String12swapValues(&s1, &s2)// Prints s1=World, s2=Hello13print("s1=\(s1), s2=\(s2)")Output
x=20, y=10 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.
=× 11(× 9)× 9"× 8,× 7\× 4&× 4_× 2:× 2{× 1