InterviewSolution
| 1. |
What do you understand about generics in ios Swift? |
|
Answer» Generics are a way to avoid code duplication. It is USUAL to repeat a method that takes one type of parameter to accommodate a parameter of a different type. Generics can be used in both functions and data types in Swift, such as classes, structures, and enumerations. func integerEquality(_ a: Int, _ b: Int) -> Bool { RETURN a == b}func stringEquality(_ a: String, _ b: String) -> Bool { return a == b}stringEquality("hello", "hello") // returns trueintegerEquality(5, 5) // returns trueFor example, the second function in the above code is a "clone" of the first, but it accepts texts rather than numbers. func commonEquality<T: Equatable>(_ a: T, _ b: T) -> Bool { return a == b}commonEquality("hello", "hello") // returns truecommonEquality(5, 5) // returns trueYou can consolidate the two functions into one and maintain type SAFETY at the same time by using generics. Given above is the way to do it in general. Because you are testing equality here, you can USE any type that implements the Equatable protocol as a parameter. This code achieves the desired outcome while preventing the use of non-typed parameters. |
|