Tuesday, April 28, 2015

Swift native Set Type

When the 1.0 version of Swift was initially released it contains native String, Array and Dictionary types that were bridged with the NSString, NSArray and NSDictionary types.  The one noticeable omission was Swift did not contain a native set type.  With the 1.2 version of Swift, Apple corrected this omission and added the Set type.

The Set type is a generic collection that is similar to the Array type.  Where the Array type is an ordered collection that may contain duplicate items, the Set type is an unordered collection where each item must be unique.

Lets look t how we would use the Set type.

Initializing a set
There are a couple of ways that we can initialize a set.  Just like the Array and Dictionary types, Swift needs to know what type of data is going to be stored in it.  This means that we must either tell Swift the type of data to store in the set or initialize it with some data so Swift can infer the data type.

Just like the Array and Dictionary types, we use the var and let keywords to declare if the set is mutable or not.  If a set is declared using the var keyword than it is mutable and if it is declared with the let keyword than it is not mutable.

//Initializes an empty Set of the String type
var mySet = Set<String>()

//Initializes a mutable set of the String type with initial values
var mySet = Set([“one”, “two”, “three”])

//Creates a non-mutable set of the String type.
let mySet = Set([“one”, “two”, “three”])

Inserting items into a Set
We use the insert method to insert an item into a set.  If we attempt to insert an item that is already there, the item will be ignored and no error will be thrown.  Here are some examples on how to insert items into a set.

var mySet = Set<String>()
mySet.insert(“One”)
mySet.insert(“Two”)
mySet.insert(“Three”)

Number of items in a Set
We can use the count property to determine the number of items in a Swift Set.  Here is an example of how to use the count method.

var mySet = Set<String>()
mySet.insert(“One”)
mySet.insert(“Two”)
mySet.insert(“Three”)
println(“\(mySet.count) items”)
The previous code will print the message “3 items” to the console because the set contains three items.

Check if a Set contains an item
We can very easily check to see if a Set contains an item by using the contains() method as shown here. 

var mySet = Set<String>()
mySet.insert(“One”)
mySet.insert(“Two”)
mySet.insert(“Three”)
var contain = mySet.contains(“Two”)
In the previous example, the contain variable is set to True because the set does contain the String “Two”.

Iterating over a Set
We can use the for statement to iterate over the items in a Set.    The following example shows how to use the for statement to iterate though the items in a set.

for item in mySet {
    println(item)
}
The previous example would print out each item in the set.

Removing items in a Set
We can remove a single item or all items in a set.  The following example shows how to remove items from a set.

//The remove method will return and remove an item from a set
var item = mySet.remove(“Two”)

//The removeAll method will remove all items from a set
mySet.removeAll()


Set Operations
Apple has provided four methods that we can use to construct a set from two other sets.  These operations can either be performed in place, on one of the sets, or used to create a new set.    These operations are:

union and unionInPlace:  Creates a set with all unique vales from both sets
subtract and subtractInPlace:  Creates a set with values from the first set that are not in the second set:
intersect and intersectInPlace:  Creates a set with values that are common to both sets
exclusiveOr and exclusiveOrInPlace:  Creates a new set with values that are in either set but not in both sets.

Lets look at some examples and see what results we get from each of these operations.  For all examples we will be using the following two sets:

var mySet1 = Set(["One", "Two", "Three", "abc"])
var mySet2 = Set(["abc","def","ghi", "One"])

Now lets look at our examples:

//newSetUnion = {"ghi", "Two", "One", "Three", "abc", "def"}
var newSetUnion = mySet1.union(mySet2)

//newSetSubtract = {"Two", "Three"}
var newSetSubtract = mySet1.subtract(mySet2)

//netSetIntersect = {"One", "abc"}
var newSetIntersect = mySet1.intersect(mySet2)

//newSetExclusiveOr = {"Two", "Three", "def", "ghi"}
var newSetExclusiveOr = mySet1.exclusiveOr(mySet2)


These four operations (union, subtract, intersect and exclusiveOr methods) add additional functionality that are not present with arrays.  Combine that with the faster lookup speeds as compared to an array, the Set can be a very useful alternative when the order of the collection is not important and the objects in a collection must be unique. 

No comments:

Post a Comment