Book Image

Swift Cookbook

By : Cecil Costa, Cecil Costa
Book Image

Swift Cookbook

By: Cecil Costa, Cecil Costa

Overview of this book

Table of Contents (18 chapters)
Swift Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a generic array initializer


In this recipe, we will learn how to use generics. This feature is used a lot in languages such as C++, Java, and C# because this way, we don't need to overload a function for each possible type that could be used in our function.

In this case, we will create a function that receives the input items and returns an array with these elements but completely shuffled.

Getting ready

Create a new Swift single view project called Chapter3 Array initializer.

How to do it...

To create a generic array initializer, follow these steps:

  1. Add a new file called ArrayInit and add this code in it:

    func arrayInit<T>(values:T...)->[T]{
        var newArray = values
        for var i=0;i < newArray.count * 2 ; ++i {
                    let pos1 = Int(arc4random_uniform(UInt32(newArray.count)))
            let pos2 = Int(arc4random_uniform(UInt32(newArray.count)))
            (newArray[pos1], newArray[pos2]) = (newArray[pos2], newArray[pos1])
        }
        return newArray
    }
  2. Now, we need to add...