Exploring Swift Sets
//
// 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
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.