What are generics? How to make a method or variable generics in Swift?

devquora
devquora

Posted On: Feb 22, 2018

 

Generic is efficient to write sensitive and reusable functions and types. It is provided in Swift 4. Most of the people use this feature to evade the risk of duplication. 'Arrays' and 'Dictionary' are also referred to generic collection. The libraries of Swift 4 are comprised of generic code.

You can add generics to a method (function) but can’t add to a variable. Understand it with an example:

func Vector3D(x: [T], y: [T], z: [T])
 {    self.xCord = x
    self.yCord = y
    self.zCord = z}

In this example, the generic created here is in a function. You can change the T with anything you want. This is how you can add generic in function.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Swift Interview Questions

    What is IOS Swift?

    Swift is an advanced language for iOS development, known for its concise and expressive syntax. It enables fast-running software and is used for developing iOS and OS X applications, making it ideal f..

    Swift Interview Questions

    What is Dictionary in Swift?

    In Swift, key-value pairs allow for efficient data storage and retrieval, functioning similarly to hash tables in other programming languages. Accessing values is straightforward by using the correspo..

    Swift Interview Questions

    Explain Enum in Swift?

    In Swift, enums define a common type for a group of related values, enabling type-safe handling within your code. Essentially, an enum groups various related values under the same umbrella, facilitati..