Swift 3 Programming Language – Generics


  • Write a name inside angle brackets to make a generic function or type.

  • Following is an Example of a Generic with the help of a function taking an type of argument and in result returns an array of same type.

func makeArry<ParameterType>(repeating item: ParameterType,
                                      times: Int) -> [ParameterType] {
    var result = [ParameterType]()
    for _ in 0..<times {
    return result

Printing knock-knock-knock with above method.

print("I'm at the door. \(makeArry(repeating: "knock", times: 3)))")
  • You can make generic forms of functions, classes, enumerations and structures.
  • Reimplemented Swift standard library's optional type.
enum OptionalValue<Wrapped> {
    case none
    case some(Wrapped)
var possibleInteger: OptionalValue<Int> = .none
print("Value of possible integer is \(possibleInteger)")
possibleInteger = .some(100)
print("Value of possible integer is \(possibleInteger)")

Output of above code is as follows.

I'm at the door. ["knock", "knock", "knock"])
Value of possible integer is none
Value of possible integer is some(100)

Click here to open actual swift-playground file for above illustration