Guide to Reference

ARC is a compile time feature that is Apple’s version of automated memory management. It stands for Automatic Reference Counting. This means that it only frees up memory for objects when there are zero strong references/ to them.

A guide to reference: when to use Strong reference, Weak reference, Unowned reference, ImplicitlyUnwrappedOptional property

 

Optional

non-Optional

Optional

strong reference &

weak reference 

 strong reference & 

unowned reference

non-Optional

strong reference &

unowned reference 

 unowned reference & 

implicitly unwrapped optional property

HW 2

“iOS application” survey

Fall 2015
Kyoung Shin Park
September 21, 2015

Individual assignment – “iOS Quantified Self Movement application” survey report (10 points 3 page)

The goal of this assignment is for you to learn the key design aspect of iPhone/iPad applications , and think about how to design if you would create your own iOS  application.

In this assignment, you are to research 2~3 subjects of your interest on mobile applications from the web sites given below (or other sites) and then summit the report (3-page) on “iOS Quantified Self Movement Application”, due by Oct 5th, 2015.

Reference:

Quantified Self http://quantifiedself.com/guide/

Fitbit (Fitbit is a small device to track your physical activity or sleep. You can wear the device all day because it easily clips in your pocket, pants, shirt, bra, or to your wrist when you are sleeping.) http://fitbit.com/

Moodpanda (MoodPanda.com is a mood tracking website and iphone app. Tracking is very simple: you rate your happiness on a 0-10 scale, and optionally add a brief twitter-like comment on what’s influencing your mood.)   http://moodpanda.com

Digifit (The Digifit ecosystem is a full suite of Apple apps that records heart rate, pace, speed, cadence, and power of your running, cycling and other athletic endeavors.) http://digifit.com/

Momento (Momento is an iPhone journal writing app. It allows you to make entries using text or photos and allows you to tag them with people from your address book, and locations from the GPS as well as category tags.)http://www.momentoapp.com

Foresquare (Foursquare is a service that helps you keep track of the places that you visit.) https://foursquare.com/

Extension

extension String {

func toFloat() -> Float {

if let unwrappedNum = Float(self) {

return unwrappedNum

}

else {

print(“Error converting \”” + self + “\” to Float”)

return 0.0

}

}

}

 

//  Double to String with Format

var text = String.localizedStringWithFormat(“%.2f”, doubleValue)

// String to Float/Double

var floatValue = text.toFloat()

Enumeration, Class, Structure

DataStructureTest.playground

// Enumeration & Class & Structure: Playground – noun: a place where people can play
// 2015.09.21 Kyoung Shin Park @ Dankook University

import Cocoa

func sayHello(personName: String = “World”) -> String {
let greeting = “Hello, ” + personName + “!”
return greeting
}
print(sayHello())
print(sayHello(“Anna”))

// Enumeration
enum Gender {
case Female
case Male
init() { // initialization
self = .Female
}
init(_ name: String)
{
switch name {
case “Female”, “여자”: self = .Female
case “Male”, “남자”: self = .Male
default: self = .Female
}
}
var description: String {
switch self {
case .Female: return “FEMALE~”
case .Male: return “MALE~”
}
}
}
var gender = Gender()
print(gender.description)
gender = Gender(“남자”)
print(gender.description)
gender = Gender.Female
gender = .Male
print(Gender.Male.description)

switch gender {
case .Female: print(“FEMALE!!”)
case .Male: print(“MALE!!”)
}

// Enum, multiple member values can appear on a single line, separated by commas
// Enum rawValue
enum Planet: Int {
case Mercury=1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
let earthID = Planet.Earth.rawValue
let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
print(“Mostly harmless”)
default:
print(“Not a safe place for humans”)
}
let aPlanet = Planet(rawValue: 7)
switch aPlanet! {
case .Earth:
print(“Mostly harmless”)
default:
print(“Not a safe place for humans”)
}
if let possiblePlanet = Planet(rawValue: 9) {
switch possiblePlanet {
case .Earth:
print(“Mostly harmless”)
default:
print(“Not a safe place for humans”)
}
} else {
print(“There isn’t a planet at position 9”)
}

// Enum associated values
enum TrainStatus {
case OnTime
case Delayed(Int)
}
var status:TrainStatus = .Delayed(5)
status = .OnTime
switch status {
case .OnTime:
print(“Train is on time”)
case .Delayed(let minutes):
print(“Train is delayed by \(minutes) minutes”)
}
// class
class Vehicle {
// stored properties
var numberOfPassengers: Int = 2
var numberOfWheels: Int = 4

// computed properties
var NumberOfWheels: Int {
get { return numberOfWheels }
set { numberOfWheels = newValue }
}
var description: String {
return “\(numberOfWheels) number of wheels”
}
}

class Bicycle: Vehicle {
override init() {
super.init()
numberOfPassengers = 1
numberOfWheels = 2
}
}

class Car: Vehicle {
// stored properties
var minVelocity: Int = 30
var accelVelocity: Int = 10
// computed properties
var speed: Int {
get {
return minVelocity + accelVelocity
}
set(newVelocity) {
accelVelocity = newVelocity – minVelocity
}
}
override init() {
super.init()
numberOfWheels = 5
}
override var description: String {
return “\(numberOfWheels) number of wheels with \(speed) speeds”
}
}
let aVehicle = Vehicle()
print(aVehicle.description)
aVehicle.numberOfWheels = 6
print(aVehicle.description)
let aBike = Bicycle()
print(aBike.description)
let aCar = Car()
print(aCar.description)
// structure
struct Frame {
var x: Int, y: Int // stored properties
var width: Int, height: Int // stored properties
var area: Int { // computed properties (getter)
return width * height
}
mutating func addWidth (width: Int) {
self.width += width // mutating modifies the value of a stored property in struct
}
}

let f = Frame(x:5, y:10, width:100, height:100)
print(f.width)
//f.width = 250 // invalid (due to let)

var g = Frame(x:5, y:10, width:100, height:100)
g.addWidth(15) // use mutating func to modify the value of a stored property in struct
print(g.width)

let h = Frame(x:5, y:10, width:100, height:100)
//h.addWidth(15) // compiler error (can’t call mutating func of struct stored in a let)
print(h.width)

Array & Dictionary

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)”)
}

String

StringTest.playground

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

import Cocoa

var letters: [Character] = [“c”, “a”, “f”, “e”]

var cafe = String(letters)

print(letters.count)

print(cafe)

print(cafe.characters.count)

let string1 = “”

var string2: NSString = “Hello”

switch (string2) {

case let string2 as NSString:

print(“string2 is NSString”)

case let string2 as String:

print(“string2 is String”)

default:

print(“None of those”)

}

var len = string2.length

var string3 = String(“Hello”)

string3 += ” World”

string3.append(Character(“!”))

var string4 = String(count: 7, repeatedValue: Character(“A”))

var string5 = NSString()

var string9 = NSString(string: “Hello”)

var string6 = NSMutableString(capacity: 10)

var total = 100

var string7 = “\(string3)! total=\(total)”

var string8: NSString = string7

//var string10: String = string3.stringByAppendingFormat(” append %@”, total)

//print(string10)

string5 = string2.stringByAppendingFormat(” append %@”, string8)

print(string8)

print(string8.description)

var str = “Hello”

var world = ” World”

var smile = “?”

var mark = “!~”

var combined = str + mark

var combined2 = (str + world).stringByAppendingString(smile)

var len2 = combined2.characters.count

// length

var length = combined.characters.count

var len3 = combined.startIndex.distanceTo(combined.endIndex)

var len4 = (combined as NSString).length

// print char of string

for char in combined.characters {

print(char)

}

print(combined2.lowercaseString)

print(combined2.uppercaseString)

print(combined2.capitalizedString)

if let range = combined.rangeOfString(“ello”) { // contains

print(“ello”)

}

else {

print(“none”)

}

var trail = combined.substringWithRange(Range<String.Index>(start: str.endIndex, end: combined.endIndex))

print(“combined = \(combined)”)

let startIndex = combined.startIndex.advancedBy(2)

let endIndex = combined.startIndex.advancedBy(5)

//combined.insert(“^”, atIndex: combined.endIndex)

//let question : Character = “?”

//combined.append(question)

//print(combined)

combined.insert(“a”, atIndex: startIndex)

combined.insertContentsOf(“bc”.characters, at: startIndex.successor())

combined.removeAtIndex(combined.endIndex.predecessor())

print(combined)

let substring = combined[startIndex..<endIndex]

print(“substring = \(substring)”)

var sub2 = combined.substringWithRange(Range<String.Index>(start: startIndex, end: endIndex))

print(sub2)

var myString = “Seoul, New York, Tokyo LA”

var myArray = myString.componentsSeparatedByString(“,”)

for s in myArray {

print(s)

}

var myArray2 = myString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: “, “))

for s in myArray2 {

print(s)

}

var num = “56.25”

if let range = num.rangeOfString(“.”) {

let wholeNum = num[num.startIndex..<range.startIndex]

print(“wholeNum=\(wholeNum)”)

num.replaceRange(num.startIndex..<range.startIndex, with: “32”)

print(“num=\(num)”)

num.removeRange(num.startIndex..<range.startIndex)

print(“num2=\(num)”)

}

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

//animals.append(“Bird”)

var animal = animals[2]

for (index, value) in animals.enumerate() {

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

}

HelloWorld

HelloWorld

-label & button & UIAlertController & autolayout

 

//

//  ViewController.swift

//  HelloWorld

//

//  Created by Park on 8/30/15.

//  Copyright © 2015 Park. All rights reserved.

//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var label1: UILabel!

 

@IBAction func showMessage(sender: AnyObject) {

label1.text = “Welcome to Swift”

let alertController = UIAlertController(title: “Welcome to my first iOS App”, message: “Hello World”, preferredStyle: UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: “OK”, style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(alertController, animated: true, completion: nil)

}

 

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}