ArrayDictionaryTest.playground
// Array & Dictionary: Playground – noun: a place where people can play
// 2015.09.20 Kyoung Shin Park @ Dankook University
import UIKit
var a = Array<String>()
var b = [String]()
var c = [Int](count: 3, repeatedValue: 1)
let animals = [“Giraffe”, “Cow”, “Dog”, “Cat”]
//animals.append(“Bird”) // due to let
var animal = animals[1]
//var animal2 = animals[5] // due to out of bounds
for animal in animals {
print(animal)
}
for (index, value) in animals.enumerate() {
print(“animals[\(index)]=\(value)”)
}
b.append(“Egg”)
b += [“Cocoa”, “Milk”, “Flour”]
b[1…3] = [“Apple”, “Butter”]
print(b)
c.insert(4, atIndex: 1)
c.insertContentsOf([5,6], at: 2)
c.removeAtIndex(1)
c.removeRange(0..<2)
c.replaceRange(0…1, with: [8,9,7])
let sorted = c.sort { $0 < $1 }
for value in sorted {
print(value)
}
// map, filter, reduce
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var arr1 = arr.map { (x)->Int in return x+1 }
print(arr1)
var arr2 = arr.map { (x)->Int in return x*2 }
print(arr2)
var arr3 = arr.filter { (x)->Bool in return x%2 == 0 }
print(arr3)
var sum = arr.reduce(0, combine: { (result, x)->Int in return result+x } )
print(sum)
let sum2: Int = arr.reduce(0) { $0 + $1 }
print(sum2)
let stringified = arr.map { “\($0)” }
print(stringified)
// dictionary
var planets1 = Dictionary<String, Int>() //empty dictionary
var planets = [String: Int]() // empty dictionary
planets = [ “Mercury”:1, “Venus”:2
] // assign
planets[“Mars”] = 3 // append
for (key, value) in planets {
print(“\(key) = \(value)”)
}
planets[“Mars”] = 4 // replace
for (key, value) in planets {
print(“\(key) = \(value)”)
}
let earth = planets[“Earth”] // earth is an Int? (should be nil)
if earth == nil {
print(“Earth is not found”)
} else {
let earthID = earth!
print(“Earth = \(earthID)”)
}
planets[“Earth”] = 3 // append Earth
// optional binding
if let earthID = planets[“Earth”] {
print(“Earth = \(earthID)”)
}