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?

    iOS swift is an intuitive and stalwart language for the iOS. It is joyful to deal with the writing stuff in Swift. It is very advanced and its syntax is also concise and expressive too...

    Swift Interview Questions

    What is Dictionary in Swift?

    It enables you to store the key-value pairs and access the value by providing the key.It is similar to that of the hash..

    Swift Interview Questions

    Explain Enum in Swift?

    Basically, it is a type that contains a group of various related values under the same umbrella...