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.

}

}

 

 

Load apps on your iPhone using Xcode 7

https://developer.apple.com/xcode/

“Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.”

  1. Update OS X 10.10.5 (Yosemite) via App Store
  2. Download and Install Xcode 7

Download Xcode 7 beta 6 (Apple ID 로그인)

xcodeapp

3. Open Xcode 7, open Preferences and login to your Account

AppleID

4. Open the workspace/project in Xcode and build & run on the simulator

5. Plug in your iPhone and select it as the build Destination

Device

6. Make sure to set iOS Deployment Target (e.g. iOS 8.4) in Build Settings for both Project and Target

Project

Target

7.  Click on the Fix Issue for Failed to code sign xxxx

2015-09-02 20.50.25

8. If there’s no build errors, the app should now launch on your phone