Swift - Using Generic Functions

Introduction

Using generics, you can create generic swap function:

func swapItems<T>(inout item1:T, inout item2:T) {
    let temp = item1
    item1 = item2
    item2 = temp
}

Here, the function uses T as the placeholder:

func swapItems <T> (inout item1: T , inout item2:T ) {

T is the placeholder for the actual data type.

You are not limited to using T as the placeholder.

Another common placeholder name is ItemType.

If you use ItemType as the placeholder, then the function declaration would look like this:

func swapItems <ItemType> (inout item1: ItemType , inout item2: ItemType ) {

You can now call the swapItems() function just as you would when you call the swapNums() function:

Demo

func swapItems<T>(inout item1:T, inout item2:T) {
    let temp = item1
    item1 = item2/*from  w w w  . j  ava 2  s  .  c  o m*/
    item2 = temp
}

var num1 = 5
var num2 = 6
swapItems (&num1, &num2)
print("\(num1), \(num2)")   //6, 5

The compiler will infer from the type of num1 when you call the swapItems() function.

T would be of type Int.

Likewise, if you call the swapItems() function using arguments of type String, T would now be String:

Demo

func swapItems<T>(inout item1:T, inout item2:T) {
    let temp = item1
    item1 = item2/*from  www  . j  a v  a 2s .co m*/
    item2 = temp
}
var str1 = "blueberry"
var str2 = "apple"
print("\(str1), \(str2)")  //blueberry, apple

swapItems(&str1, &str2)
print("\(str1), \(str2)")  //apple, blueberry

//The same behavior applies to Double  types:

var price1 = 23.5
var price2 = 16.8
print("\(price1), \(price2)")  //23.5, 16.8
swapItems(&price1, &price2)
print("\(price1), \(price2)")  //16.8, 23.5

Related Topic