sandbox

print((200 * 7)/2)
print("Hello from the ios team")

variable function

var name = "jack"
var introduction = "I'm \(name),"

var nobleGoal = "skill up"
var yourDream = " and I used to dream of building an app that could \(nobleGoal)."

print(introduction + yourDream)

try again

var language = "swift"
var epiphany = " Then, one day, I discovered \(language)."

print(epiphany)

concatenate variable each other

var language = "java"
var nobleGoal = "AR"

var condition = "Then I knew that, programming in \(language). "
var result = "I could make my dream of \(nobleGoal) a realilty."

var end = condition + result
print(end)

function

func averageScore(firstScore: Double, secondScore: Double, thirdScore: Double){
	let totalScore = firstScore + secondScore + thirdScore
	print(totalScore/ 3)
	}
func nameOfFunction(/* parameters */) -> Type {
	var valueToReturn: Type
	return valueToReturn
}

func calculateTip(priceOfMeal: Double) -> Double {
	return priceOfMeal * 0.15
}

func isValidLength(password: String) -> Bool {
	if password.characters.count >= 8 {
		return true
	} else {
		return false
	}
}

func calculateTip(priceOfMeal: Double -> Double{
	return priceOfMeal * 0.15
	})

let priceOfMeal = 43,27

let tip = calculateTip(priceOfMeal: priceOfMeal)

what’s string about

let theTrueth = "Money can't buy me love."
theTruth.characters.count

var forwardString = "spoons"
var charactersReversed = forwardString.characters.reversed()

for character in charactersReversed {
	print ("\(character)")
}

let similarTruth = "can't buy me"
var birthdayCheer = "Happy Birthday!"
print(birthdayCheer)

var name = "Kate"
var customizedBirthdayCheer = "Happy Birthday, \(name)!"
print(customizedBirthdayCheer)
var doggyDiet = "Mia eats 10 lbs of dog food per month."

var dogName = "Zebedee"
var lbsPerMonth: Double = 25

doggyDiet = "\(dogName) eats \(lbsPerMonth)lbs of dog food per month"

print(doggyDiet)

var kilosInALb = 0.45
var metricDoggyDiet = "\(dogName) eats \(kilosInALb * lbsPerMonth)kilos of dog food per month"

print(metricDoggyDiet)
let monkeyString = "I saw a monkey."
let thiefString = "He stole my iPhone."

var monkeyStringWithEmoji = "I saw a *."
var thiefStringWithEmoji = "He stole my *."

var forwardString = "time"
var charactersReversed = forwardString.characters.reversed()

for character in charactersReversed {
	print("\(character)")
}

let numOfPennies = 567
let dollarInt = numofPennies/100
let dollarsAndCentsString = "$\(dollarInt).\(numOfPennies % 100)"

let monkeyString = "I saw a monkey."
let thiefString = "He stole my iPhone."
var sillyMonkeyString = monkeyString + "" + thiefString

replacingOccurences(of: with:)

sillyMonkeyString.contains("key")

Different types of variables

var petsAge = 12
var myMiddleInitial: Character = "A"
var numberOfWheels: Int = 4
var centimetersOfRainfall: Float = 5.5
var pi: Double = 3.14159265359
var letterOfTheDay: Character = "z"
var myFavoriteAnimal: String = "nudibranch"
var rainingOutside: Bool = true
let encouragement = "you can do it!"
var customizedEncouragement = "you can do it, stephanie!"
customizedEncouragement = "you can do it, Ryder!"

let birthYear = 2008
var currentYear = 2017
var age = currentYear - birthYear
currentYear = 2017
age = currentYear - birthYear

Names cannot contain whitespace characters, mathematical symbols, arrows and [a few other obscure characters].
Names must begin with an uppercase or lowercase letter A through Z, an underscore, or [a few other less common options].

let theTrue = "Money can't buy me love."

var characterPoorString = ""
let stringWithPotential = String()

Sandbox

// test code here!
print((200 * 7)/2)

print("hello from iOS team")

var question = "Ready to write your first lines of Swift code?"
print(question)

var response = "Yeah! I'm ready!"
print(response)
var numberOfServingsForRecipe = 4
var desiredNumberOfServings = 8

var servingsFactor = desiredNumberOfServings/numberOfServingsForRecipe

var poundsOfTomatoesForRecipe = 2
var amountToUseToday = poundsOfTomatoesForRecipe * servingsFactor

print(amountToUseToday)

browser app

screen-shot-2016-11-26-at-07-06-42

import UIKit

class ViewController: UIViewController, UIWebViewDelegate, UITextFieldDelegate {
    
    
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var backButton: UIBarButtonItem!
    @IBOutlet weak var forwardButton: UIBarButtonItem!
    @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let topBorder = CALayer()
        topBorder.frame = CGRectMake(0, 0, self.webView.frame.size.width, 1)
        topBorder.backgroundColor = UIColor.lightGrayColor().CGColor
        self.webView.layer.addSublayer(topBorder)
        self.webView.delegate = self
        self.textField.delegate = self
        
        self.webView.delegate  = self
        self.textField.delegate = self
        
        // string -> NSURL -> NSURLRequest -> webView.loadRequest
        let startUrl = "http://google.com"
//        if let url = NSURL(string: startUrl){
//            let urlRequest = NSURLRequest(URL: url)
//            self.webView.loadRequest(urlRequest)
//        }
        self.jumpToUrl(startUrl)
        self.setupButtonsEnabled()
        self.activityIndicatorView.hidesWhenStopped = true
    }
    
    func jumpToUrl(urlString: String){
        if let url = NSURL(string: urlString){
            let urlRequest = NSURLRequest(URL: url)
            self.webView.loadRequest(urlRequest)
        } else {
            self.showAlert("Invalid URL")
        }
    }
    
    func showAlert(message: String){
        let alertController = UIAlertController(title: "Error", message:message, preferredStyle: .Alert)
        let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(defaultAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        var urlString = self.textField.text
        urlString = urlString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        if urlString == "" {
            // alert
            self.showAlert("please enter URL")
        } else {
            if urlString.hasPrefix("http://") && !urlString.hasPrefix("https://") {
                urlString = "http://" + urlString
            }
            self.jumpToUrl(urlString)
            self.setupButtonsEnabled()
        }
        self.textField.resignFirstResponder()
        return true
    }
    
    func setupButtonsEnabled() {
        self.backButton.enabled = self.webView.canGoBack
        self.forwardButton.enabled = self.webView.canGoForward
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        self.webView.stopLoading()
        self.activityIndicatorView.stopAnimating()
        
        if error.code != NSURLErrorCancelled {
            self.showAlert("Network Error")
        }
        self.updateUrlLocation()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        self.activityIndicatorView.startAnimating()
    }
    
    func updateUrlLocation(){
        if let urlString = self.webView.request?.URL?.absoluteString {
            self.textField.text = urlString
        }
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        self.activityIndicatorView.stopAnimating()
        self.setupButtonsEnabled()
        self.updateUrlLocation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func goBack(sender: AnyObject) {
        self.webView.goBack()
    }
    
    @IBAction func goForward(sender: AnyObject) {
        self.webView.goForward()
    }
    
    @IBAction func reload(sender: AnyObject) {
        self.webView.reload()
    }

}

string -> NSURL -> NSURLRequest -> webView.loadRequest

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var backButton: UIBarButtonItem!
    @IBOutlet weak var forwardButton: UIBarButtonItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // string -> NSURL -> NSURLRequest -> webView.loadRequest
        let startUrl = "http://hogehoge.com"
        if let url = NSURL(string: startUrl){
            let urlRequest = NSURLRequest(URL: url)
            self.webView.loadRequest(urlRequest)
        }
        
    }

姓名診断 app

screen-shot-2016-11-26-at-02-38-19
tips
ctl + button -> segue: show
seque identifier -> class name
command + = -> size調整
file -> new file -> Cocoa Class : 新しいclassを生成 -> utility custom classでclass設定

import UIKit

class ViewController: UIViewController {

    
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.textField.text = ""
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func showAlert() {
        let VERSION: Float = (UIDevice.currentDevice().systemVersion as NSString).floatValue
        if VERSION >= 8.0 {
            let alertController = UIAlertController(title: "Error", message: "Please enter your name", preferredStyle: .Alert)
            let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
            alertController.addAction(defaultAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        } else {
            let alert = UIAlertView()
            alert.title = "Error"
            alert.message = "Please enter your name"
            alert.addButtonWithTitle("OK")
            alert.show()
        }
    }
    
    override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
        if identifier == "showResult" {
            if self.textField.text == "" {
                self.showAlert()
                return false
            }
            return true
        }
        return true
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showreResult" {
            let resultViewController: ResultViewController = segue.destinationViewController as! ResultViewController
            resultViewController.myName = self.textField.text
            self.textField.resignFirstResponder()
        }
    }
    
}


import UIKit

class ResultViewController: UIViewController {

    var myName: String = ""
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!
    
    override func viewDidLoad(){
        super.viewDidLoad()
        self.nameLabel.text = "\(self.myName)の点数は..."
        
        let score = arc4random_uniform(101)
        self.scoreLabel.text = "\(score)点"
        
    }
    
    
}

omikuji app

swiftではarcNrandom_uniform(UInt32(hoge.count))でランダムに数値を生成します。

Tips
command + option + 0: utility 非表示
launch screen -> main.storyboardに変更可能

screen-shot-2016-11-26-at-01-32-40

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!
    
    
    @IBAction func getOmikuji(sender: AnyObject) {
        let results = [
            "大吉",
            "吉",
            "中吉",
            "凶",
            "大凶"
        ]
        
        // arc4random_uniform(n + 1)
        let random = arc4random_uniform(UInt32(results.count))
        
        if random == 0 {
            self.myLabel.textColor = UIColor.redColor()
        } else {
            self.myLabel.textColor = UIColor.blackColor()
        }
        
        self.myLabel.text = results[Int(random)]
    }
    
    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.
    }


}

Swift coding

untitled

//var s: String?
//s = nil

let name: String? = "yamada"
let msg = "hello " + name!

if name != nil {
    let msg = "hello " + name!
}

if let s = name {
 let msg = "hello " + s
}

var label: String!
label = "score"
println(label)

function

//func sayHi(){
//    println("hi")
//}
//sayHi()

func sayHi(name: String){
    println("hi " + name)
}
sayHi("satoshi")

func sayHi(myname name: String){
    println("hi " + name)
}
sayHi(myname: "satoshi")

func sayHi(#name: String = "jiro"){
    println("hi " + name)
}
sayHi(name: "satoshi")

列挙型

enum Result {
    case Success
    case Error
    func getMessage() -> String {
        switch self {
        case .Success:
            return "OK"
        case .Error:
            return "OK"
        }
    }
}

var r: Result

r = Result.Success
r = .Success

Result.Error.rawValue

class

class User {
    var name: String
    var score: Int = 0
    init(name: String){
        self.name = name
    }
    func updrade() {
        score++
    }
}

var tom = User(name: "Tom")
tom.name
tom.score
tom.updrade()
tom.score

継承

class User {
    var name: String
    var score: Int = 0
    init(name: String){
        self.name = name
    }
    final func upgrade() {
        score++
    }
}

class AdminUser: User {
    func reset(){
        score = 0
    }
    override func upgrade(){
        score += 3
    }
}

protocol

protocol Student {
    var studentId: String { get set }
    func study()
}

class User: Student {
    var name: String
    var score: Int = 0
    var studentId: String = "hoge"
    func study(){
        println("studying.....")
    }
    init(name: String){
        self.name = name
    }
    func upgrade() {
        score++
    }
}



var tom = User(name: "Tom")
tom.name
tom.score
tom.upgrade()
tom.score

willSet, didSet

class User {
    var name: String
    var score: Int = 0 {
        willSet{
            println("\(score) -> \(newValue)")
        }
        didSet {
            println("\(oldValue) -> \(score)")
        }
    }
    var level: Int {
        get{
            return Int(score / 10)
        }
        set {
            score = Int(newValue * 10)
        }
    }
    init(name: String){
         self.name = name
        }
    func upgrade() {
        score++
    }
}

optional chaining

class User {
    var blog: Blog?
}

class Blog {
    var title = "My Blog"
}

var tom = User()
tom.blog = Blog()
tom.blog?.title

if let t = tom.blog?.title {
    println(t)
}

type casting

class User {
    var name: String
    init(name: String){
        self.name = name
    }
}
class AdminUser: User {}

let tom = User(name: "Tom")
let bob = AdminUser(name: "Bob")
let steve = someUser()

let users: [AnyObject] = [tom, bob, steve]

for user in users {
    if let u = user as? AdminUser {
        println(u.name)

構造体

struct UserStruct {
    var name: String
    var score: Int = 0
    init(name: String){
        self.name = name
    }
    mutating func upgrade(){
        score++
    }
}

拡張

extension String {
    var size: Int {
        return countElements(self)
    }
    func dummy() -> String {
        return "dummy"
    }
}

var s: String = "hoge"
s.size
s.dummy()

generics

func getArray(item: T, count: Int) -> [T]
{
    var result = [T]()
    for _ in 0..