1.

What are generics in swift and write its usage?

Answer»

A major feature of Swift is generics, and much of the Swift standard library is written in generic code. Swift's 'Array' and 'Dictionary' types, for example, constitute generic collections. Generic code allows you to create flexible, reusable functions and types that work with any data TYPE. You can create code that does not GET too specific about UNDERLYING data types, resulting in cleaner code. 

Example: 

func Swapping(x: inout Int, y: inout Int)  {       let temp = x    x = y    y = temp } var num1 = 10 var num2 = 50 print("Before Swapping: \(num1) and \(num2)") Swapping(x: &num1, y: &num2) print("After Swapping: \(num1) and \(num2)")

Output: 

Before Swapping: 10 and 50 After Swapping: 50 and 10

In the above example, we have defined a function called Swapping() to SWAP integers. It takes two parameters x and y of int type. As seen in the output, the values of x and y are EXCHANGED after the swapping.



Discussion

No Comment Found