Swift Generics

Generics code are useful to define data type of variable which can store any data value. That is very important because this is provide higher level reusability of codes.

func checkTypeInfo<T>(_ value : T){
    print(type(of:value))
}
let textData: String = "Swift Programming"
let numberData: Int = 11
checkTypeInfo(textData) //String 
checkTypeInfo(numberData) //Int

Output

String
Int
struct MyQueue<T>{

    var data  = [T]() //Create Queue

    mutating func enQueue(_ value : T){

        data.append(value)
    }

    mutating func deQueue()->T?{
        if(data.isEmpty){
            return nil
        }
        else{
            let removeData = data[0]
            data.removeFirst()
            return removeData
        }
    }

    //Print element of Queue
    func display(){
        for i in data {
            print(i,terminator : "  ")
        }
    }
}

var coins = MyQueue<Int>()
var days = MyQueue<String>()

coins.enQueue(10)
coins.enQueue(20)
coins.enQueue(50)



//Insert Day element
days.enQueue("Sunday")
days.enQueue("Monday")
days.enQueue("Tuesday")
days.enQueue("Wednesday")
days.enQueue("Thursday")
days.enQueue("Firday")
days.enQueue("Saturday")

print("All Coins Elements : ",terminator : "  ")
coins.display()

print("\nAll Days Elements : ",terminator : "  ")
days.display()

print("\nRemove coin element : \(coins.deQueue()!)")

print("Remove days element : \(days.deQueue()!)")


print("\nCoins Elements : ",terminator : "  ")
coins.display()

print("\nDays Elements : ",terminator : "  ")
days.display()

Output

All Coins Elements :   10  20  50  
All Days Elements :   Sunday  Monday  Tuesday  Wednesday  Thursday  Firday  Saturday  
Remove coin element : 10
Remove days element : Sunday

Coins Elements :   20  50  
Days Elements :   Monday  Tuesday  Wednesday  Thursday  Firday  Saturday


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved