ArrayTest

//: Playground – noun: a place where people can play

// Swift2 string, array

// Kyoung Shin Park (2016 Fall)

import UIKit

//string

let hello = “Hello”

let world = “World”

let smile = “?”

var h = hello + ” ” + world // “Hello World”

h += “, Swift” // “Hello World, Swift”

h.append(Character(“!”)) // “Hello World, Swift!”

var strH = h.stringByAppendingString(smile) // Hello World, Swift!

print(strH)

print(strH.uppercaseString)

var len = hello.characters.count // “Hello” 5

var len2 = hello.startIndex.distanceTo(hello.endIndex) // “Hello” 5

for s in hello.characters { // using foreach

print(“\(s)”)

}

for i in 0..<hello.characters.count { // using String.Index & range

print(“\(i): \(hello[hello.startIndex.advancedBy(i)])”)

}

for (index, value) in hello.characters.enumerate() { // using array & tuple

print(“\(index): \(value)”)

}

// array

func fillArray(inout arr: [Int]) {

    arr.appendContentsOf([1, 2, 3])

}

var myArray : [Int] = []

fillArray(&myArray)

print(myArray)

 

var a = Array<String>()

var b = [String]()

var c = [Int](count: 3, repeatedValue: 1)

var animals = [“Giraffe”, “Cow”, “Dog”, “Cat”]

animals.append(“Bird”)

var animal = animals[1]

for animal in animals { // using foreach

print(animal)

}

for i in 0..<animals.count { // using index & range

print(“animals[\(i)]=\(animals[i])”)

}

for (index, value) in animals.enumerate() { // using tuple & enumerate

print(“animals[\(index)]=\(value)”)

}

b.append(“Egg”)

print(b)

b += [“Cocoa”, “Milk”, “Flour”]

print(b)

b[1…3] = [“Apple”, “Butter”]

print(b)

c.insert(4, atIndex: 1)

print(c)

c.insertContentsOf([5,6], at: 2)

print(c)

c.removeAtIndex(1)

print(c)

c.removeRange(0..<2)

print(c)

c.replaceRange(0…1, with: [8,9,7])

print(c)

let sorted = c.sort { $0 < $1 }

for value in sorted {

print(value)

}

// http://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/

// collections – map, filter, reduce

let odd: [Int] = sorted.filter { $0 % 2 != 0}

print(odd)

let stringified: [String] = sorted.map { “\($0)” }

print(stringified)

let squares: [Int] = sorted.map { $0 * $0 }

print(squares)

let sum: Int = [1, 2, 3].reduce(0) { $0 + $1 } // adds up the numbers in the Array

print(sum)