Exploring Swift Sets

Updated vegaseat 1 Tallied Votes 279 Views Share

Like most modern languages Swift has sets and set operations. Here is a quick look.

Coming in the fall of 2015 ...
Swift2 replaces println() with just print() that has a newline default. The sort of thing that Python3 did to print(). There are some other syntax changes.
Good news, there will be a Swift 1-to-2 migrator utility to change Swift1 syntax to Swift2 syntax.

//
//  main.swift
//  Swift_sets101
//
// exploring Apple's Swift language
// using Swift version 1.2   vegaseat   21jul2015
//

import Foundation


// sets ...

// a type must be hashable in order to be stored in a set
// immutable types like String, Int, Double, and Bool are hashable
// sets have unique elements in "hash" order
var emptySet = Set<Int>()

// convert an array to a set
// removes all duplicates, does not keep same order
var arr = [1, 2, 3, 4, 5, 3, 2]
var set = Set(arr)
println(set)  // [5, 2, 3, 1, 4]

// insert another unique element
set.insert(22)
println(set)  // [5, 22, 2, 3, 1, 4]

// remove an element
set.remove(3)  // 3, returns nil if element not found
println(set)   // [5, 22, 2, 4, 1]

for element in sorted(set) {
    println(element)
}
/*
1
2
4
5
22
*/


var colorSet1 = Set(["red", "orange", "silver", "blue"])
var colorSet2 = Set(["gold", "blue", "green", "magenta"])

// these ops create new sets
// combine the 2 sets
println(colorSet1.union(colorSet2))
/*
["red", "green", "silver", "magenta", "orange", "gold", "blue"]
*/

// this will give an error
// use union() instead
//println(colorSet1 + colorSet2)

// colors that the 2 sets have in common
println(colorSet1.intersect(colorSet2))  // ["blue"]

// colors that are in set1 and not in set2
println(colorSet1.subtract(colorSet2))  // ["silver", "red", "orange"]

// colors that are in either set but not both sets
println(colorSet1.exclusiveOr(colorSet2))
/*
["silver", "magenta", "gold", "red", "green", "orange"]
*/


// a practical problem that can be solved with sets
// a cook has a list of ingredients from a recipe
var ingredients = ["flour", "butter", "almonds", "sugar", "cinnamon"]

// items in the kitchen's pantry. spice drawer and cooler
var pantry = ["flour", "sugar", "pecans", "beans", "olive oil"]
var drawer = ["sage", "cinnamon", "salt", "pepper", "garlic"]
var cooler = ["milk", "butter", "beef", "chicken", "fish", "liver"]
var kitchen = pantry + drawer + cooler

// check if all ingredients are in the kitchen
// show any ingredients if they are missing
var ingredientSet = Set(ingredients)
var kitchenSet = Set(kitchen)
// new set has items in ingredientSet that are not in the kitchenSet
var missingSet = ingredientSet.subtract(kitchenSet)

if missingSet.count == 0 {
    println("All ingredients are in the kitchen!")
} else {
    println("Missing ingredients are \(missingSet)")
}
/*
Missing ingredients are ["almonds"]
*/
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another code example for the use of sets ...

// get the unique words in the following sentences
var str1 = "man who run in front of car get tired "
var str2 = "man who run behind car get exhausted "
var str3 = str1 + str2

// split string at spaces
var strArray = str3.componentsSeparatedByString(" ")
// set of unique words
var strSet = Set(strArray)

for word in sorted(strSet) {
    println(word)
}

/*
behind
car
exhausted
front
get
in
man
of
run
tired
who
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.