Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save carlynorama/1f6e54363fd5447e3349 to your computer and use it in GitHub Desktop.

Select an option

Save carlynorama/1f6e54363fd5447e3349 to your computer and use it in GitHub Desktop.
Whole collections learning scratch pad, Swift 2.1
//: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
import UIKit
var str = "Hello, playground"
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
someInts.append(3)
print("someInts is of type [Int] with \(someInts.count) items.")
someInts = []
print("someInts is of type [Int] with \(someInts.count) items.")
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
var comboArray = threeDoubles + anotherThreeDoubles
var shoppingList: [String] = ["Eggs", "Milk"]
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
shoppingList += ["Baking Powder"]
shoppingList += ["chocolate","flour"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
shoppingList[4...6] = ["Bananas", "Apples"]
shoppingList.insert("Maple Syrup", atIndex: 2)
let apples = shoppingList.removeLast()
for item in shoppingList {
print(item)
}
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
shoppingList.removeAll(keepCapacity: true)//default is false
var newArray = [12, 24, 36]
print("someInts is of type ?? with \(newArray.count) items.")
newArray.removeAtIndex(1)
newArray.append(newArray[0] * newArray[1])
//sets must be Hashable? protocol from Swiftโ€™s standard library
//Reflexivity, Symmetry, Transistivity
var letters = Set<Character>()
letters.insert("a")
print("letters is of type Set<Character> with \(letters.count) items.")
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// Also string inferrable if all the same
//var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
favoriteGenres.insert("Jazz")
//removedGenre be set to "Rock" if it is in there, nil if it is not
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
for genre in favoriteGenres {
print("\(genre)")
}
//empty or < is a to z (increasing), > decreasing
for genre in favoriteGenres.sort(>) {
print("\(genre)")
}
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sort()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
evenDigits.union(oddDigits).sort(>)
oddDigits.intersect(evenDigits).sort()
oddDigits.intersect(singleDigitPrimeNumbers).sort()
oddDigits.subtract(singleDigitPrimeNumbers).sort()
singleDigitPrimeNumbers.subtract(oddDigits).sort()
oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()
singleDigitPrimeNumbers.exclusiveOr(oddDigits).sort()
let houseAnimals: Set = ["๐Ÿถ", "๐Ÿฑ"]
let farmAnimals: Set = ["๐Ÿฎ", "๐Ÿ”", "๐Ÿ‘", "๐Ÿถ", "๐Ÿฑ"]
let cityAnimals: Set = ["๐Ÿฆ", "๐Ÿญ"]
houseAnimals.isSubsetOf(farmAnimals)
farmAnimals.isSupersetOf(houseAnimals)
farmAnimals.isDisjointWith(cityAnimals)
farmAnimals.isDisjointWith(houseAnimals)
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
print("The airports dictionary contains \(airports.count) items.")
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
airports["LHR"] = "London"
airports["LHR"] = "London Heathrow"
airports["APL"] = "Apple International"
airports["APL"] = nil
if let removedValue = airports.removeValueForKey("DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
for airportNames in airports.values {
print("Airport Names: \(airportNames)")
}
let yourDict = ["One": "X", "Two": "B", "Three": "Z", "Four": "A"]
let sortedKeys = yourDict.keys.sort({ (firstKey, secondKey) -> Bool in
return yourDict[firstKey] < yourDict[secondKey]
})
let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
let sortedKeys2 = Array(dictionary.keys).sort(<)
let sortedKeysAndValues = dictionary.sort { print("tod:\($0.0), \($0.1)"); return $0.0 < $1.0 }
let wordDict = [
"c" : "banna",
"Z" : [3, 4],
"4" : [3, 4],
"a" : [5, 6],
"q" : "banna",
"W" : [3, 4],
"2" : [3, 4],
"H" : [5, 6]
]
let sortedDict = wordDict.sort { $0.0 < $1.0 }
print("\(sortedDict)")
let myDictionary = [
"20" : "banna",
"60" : "apple",
"30" : "cucumber",
"10" : "starfruit"
]
//given that sort takes 2 arguments let's say sort(a,b)
//compare the 0th (a) with the 1st (b), using the key (0 after decimal)
let sortedByKeyDictionary = myDictionary.sort { $0.0 < $1.0 }
print("\(sortedByKeyDictionary)")
//given that sort takes 2 arguments let's say sort(a,b)
//compare the 0th (a) with the 1st (b), using the value (1 after decimal)
let sortedByValueDictionary = myDictionary.sort { $0.1 < $1.1 }
print("\(sortedByValueDictionary)")
print(myDictionary["20"]!)//without ! Prints Optional("banna")
let codeValueDict = ["us": "$", "it": "โ‚ฌ", "fr": "โ‚ฌ"]
let sortedKeysAndValues2 = codeValueDict.sort { $0.0 < $1.0 }
print("\(sortedKeysAndValues2)")
let keys = sortedKeysAndValues2.map {$0.0 }
print("\(keys)")
let values = sortedKeysAndValues2.map {$0.1 }
print("\(values)")
let myMenu = [
"french fries" : 1.25,
"veggie burger" : 5.95,
"Soda" : 1.65
]
//var totalCost = myMenu["french fries"]! + myMenu["Soda"]! + myMenu["veggie burger"]!
//let prices = myMenu.map{$0.1}
//print("\(prices)")
//let totalCost2 = prices.reduce(0, combine: +)
//let totalCost = myMenu.values.reduce(0, combine: +)
print("The cost of your meal is \(myMenu.values.reduce(0, combine: +))")
print("Actually, I'm charging you 3.65 extra, so \(myMenu.values.reduce(3.65, combine: +))")
["one","two","three"].reduce("",combine:{$0 + $1})
let numbers = [Int](0..<10)
let total = numbers.reduce(0, combine: +)
//Concat strings
print(["one","two","three"].reduce("This string comes before: ",combine:{$0 + $1}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment