Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Generic Function in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 550
    Comment on it

    Hi,

     

    Swift has a powerful feature of writing generic function as in Java which was missing in objective C.
    It makes our code flexible and reusable for various types, meaning it can work with any data type. For similar logics and problems generic is a solution.

    Let me explain you here:

    If we have two STRINGS and need to be swapped then we write function something like:

    func swapTwoStrings(firstString: inout  String , secondString: inout String) {
          let temporaryString = firstString
          firstString = secondString
          secondString = temporaryString
    }

     

    Now if we again need to swap two INTEGERS then we write a function in similar manner as written above:

    func swapTwoNumbers(firstNumber: inout  Int , secondNumber: inout Int) {
          let temporaryNumber = firstNumber
          firstNumber = secondNumber
          secondNumber = temporaryNumber
    }


    You’ve noticed that we are using same logic to swap strings and Integers or in other words both functions are identical. Now it may be a case that we may need swapping for other types as well. In that case it’s very useful and flexible to write a single function(so called generic function) that can handle all types to swap values.

    Example:

    func swapValues<T>(first: inout  T, second: inoutT) {
         let temporary = first
         first = second
         second = temporaryA
    }

    Although this function is identical to functions used for swapping integers and strings with only difference is that we are using a placeholder T(say, for now) instead of an actual type. Placeholder(T, you can use any placeholder name) should be used in angle brackets because these brackets tells compiler that T is a placeholder type name. The placeholder doesn’t say anything what T should be but both first and second parameter should be of T kind.
    Now using generic swapping function you can swap various type of values, provided both parameters are of same type.

     

    Thank You

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: