alertcontroller

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if identifier == "showResult" {
            guard self.nameText.text != "" else {
                let alertController = UIAlertController(title: "Error", message: "Please enter your name", preferredStye: alert)
                let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                alertController.addAction(defaultAction)
                self.present(alertController, animated: true, completion: nil)
                return false
            }
            return true
        }
        return true
    }

text fieldの値をview controllerに渡す

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let identifier = segue.identifier else {
            return
        }
        if identifier == "showResult"{
            let resultVC = segue.destination as! ResultViewController
            resultVC.myName = self.nameText.text!
        }
    }

iphone8のemulatorの立ちあがりが異常に遅いんだが。。。

あれ?

失敗してるーーーーーーーーーーーーーー
あ、いいのか

macOSをSierraにupdateしてx-codeもupdate

Sierraを入れられず、mac book買い換えないとダメかと思いmac bookを物色していましたが、ストレージ周りをいろいろ整理していたら、何故かいけましたね。一安心。今日が日曜でなければ一杯飲んでたところ。
Xcodeが最新でないと、swiftの書き方だけでなく、あらゆる面で死活問題でしたので。。。

強制停止はcomand + option + esc

x-code 9.3.1 入りました。半日かかった。ヒャッホー

ios 新しいclass file

file -> new -> file -> cocoa file

新しく作ったcocoa classをview controllerと紐づける

ふむふむ

prepare func

class ViewController: UIViewController {

    @IBOutlet weak var nameText: UITextField!
    
    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.
    }
    
    ovrride func prepare(for seque: UIStoryboardSeque, sender: Any?)
    {
        let resultVC = seque.destination as! ResultViewController
        resultVC.myName = self.nameText.text!
    }


}

arc4random_uniform

@IBAction func getOmikuji(sender: AnyObject) {
        // 0 - n
        // arc4random_uniform(n + 1)
        let random = arc4random_uniform(10)
        
        self.myLabel.text = String(random)
    }

おーおーお

@IBOutlet weak var myLabel: UILabel!
    
    @IBAction func getOmikuji(sender: AnyObject) {
        // 0 - n
        // arc4random_uniform(n + 1)
        let results = ["大吉", "中吉","吉", "大凶"]
        let random = arc4random_uniform(UInt32(results.count))
        
        self.myLabel.text = results[Int(random)]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        myLabel.layer.borderColor = UIColor.orange.cgColor
//        myLabel.layer.borderWidth = 5
//        myLabel.layer.cornerRadius = 50
        myLabel.layer.masksToBounds = true
        myLabel.layer.cornerRadius = myLabel.bounds.width / 2
        
        
        // Do any additional setup after loading the view, typically from a nib.
    }

swift basic3

generic

// Generics

func getThree<T>(x: T){
    print(x)
    print(x)
    print(x)
}

getThree(x: 5)
getThree(x: "Hello")
getThree(x: 2.3)

guard

// func sayHi(_ msg: String?){
//     if let s = msg{
//         print(s)
//     } else {
//         print("value is not set!")
//     }
// }
// sayHi(nil)
// sayHi("hello")

func sayHi(_ msg: String?){
    guard let s = msg else{
        print("value not set!")
        return
    } 
    print(s)
}

sayHi(nil)
sayHi("hello")

例外処理

// 例外処理

enum LoginError: Error{
    case emptyName
    case shortName
}

class User {
    let name: String
    init(_ name: String){
        self.name = name
    }
    func login() throws{
        guard name != "" else {
            throw LoginError.emptyName
        }
        guard name.characters.count > 5 else {
            throw LoginError.shortName
        }
        print("login success")
    }
}
let tom = User("tom")

do {
    try tom.login()
} catch LoginError.emptyName {
    print("please enter your name")
} catch LoginError.shortName{
    print("too short")
}

optional

// class User {
//     var name: String = ""
// }

// let user: User
// user = User()
// user.name = "him"
// let s = user.name.uppercased()
// print(s)

class User {
    var name: String = ""
}

let user: User?
user = User()
user?.name = "him"
if let s = user?.name?.uppercased(){
    print(s)
}
// Implicity Unwrapped Optional

// var msg: String?
var msg: String!
msg = "hello"

// if msg != nil {
//     print(msg!)
// }

print(msg)

swift basic 2

protocol

// protocol

protocol Printable {
    var type: String { get }
    var count : Int { get set}
    func printout()
}

class User : Printable{
    let name: String // property
    let type = "Laser"
    var count = 0
    init(_ name: String){
        self.name = name
    }
    func printout(){
        count += 1
        print("\(type): \(count)")
    }
}

let tom = User("tom")
tom.printout()
tom.printout()
tom.printout()

extension

// extension

extension String {
    var length: Int {
        return self.characters.count
    }
}

let msg = "hello"
print(msg.characters.count)
print(msg.length)

protocol Printable {
    func printout()
}

class User{
    let name: String // property
    init(_ name: String){
        self.name = name
    }
}
// extension

extension String {
    var length: Int {
        return self.characters.count
    }
}

let msg = "hello"
print(msg.characters.count)
print(msg.length)

protocol Printable {
    func printout()
}

extension Printable {
    func printout(){
        print("now printing...")
    }
}

class User: Printable{
    let name: String // property
    init(_ name: String){
        self.name = name
    }
}
let tom = User("tom")
tom.printout

値の参照

// Int, Double, Array .. ->値型
// Class -> 参照型

// var original = 10
// var copy = original // original

// original = 20
// print(original)
// print(copy)

class User{
    var name: String // property
    init(_ name: String){
        self.name = name
    }
}

var original = User("tom")
var copy = original // originalのデータが格納されている場所
original.name = "bob"
print(original.name)
print(copy.name)

構造体

// 構造体
// クラスと同機能

struct User{
    var name: String // property
    init(_ name: String){
        self.name = name
    }
    mutating func changeName(){
        self.name = name.Uppercased()
    }
}

var original = User("tom")
var copy = original // originalの値
original.name = "bob"
print(original.name)
print(copy.name)
// 列挙型

enum Direction {
    case right
    case left
}

// var dir: Direction
// // dir = Direction.right
// dir = .right

// switch(dir){
//     case .right:
//         print("right")
//     case .left:
//         print("left")
// }
enum Direction: Int {
    case right = 1
    case left = -1
}
print(Direction.right.rawValue)

swift basic

class User {
    let name: String // property
    var score: Int
    // init(name: String, score: Int){
    init(_ name: String,_ score: Int){
        self.name = name
        self.score = score
    }
    init(){
        self.name = "bob"
        self.score = 30
    }
}
// let tom = User(name: "tom", score: 23)
let tom = User("tom", 23)
print(tom.name)
print(tom.score)

let bob = User()
print(bob.name)
print(bob.score)

計算プロパティ

class User {
    let name: String // property
    var score: Int
    var level: Int{
        get {
            return Int(score / 10)
        }
        set {
            if newValue >= 0 {
                score = newValue * 10
            }
        }
    }
    init(_ name: String,_ score: Int){
        self.name = name
        self.score = score
    }
    init(){
        self.name = "bob"
        self.score = 30
    }
}

let tom = User("tom", 23)
print(tom.level)
tom.level = 5
print(tom.score)

willSetとdidSet

    let name: String // property
    var score: Int {
        willSet {
            // before change
            print("\(score) -> \(newValue)")
        }
        didSet {
            // after change
            print("Changed: \(score - oldValue)")
            
        }
    }
    init(_ name: String,_ score: Int){
        self.name = name
        self.score = score
    }
}

let tom = User("tom", 23)
tom.score = 53
tom.score = 40

method

class User {
    let name: String // property
    var score: Int
    init(_ name: String,_ score: Int){
        self.name = name
        self.score = score
    }
    // クラスに紐付いた関数はメソッド
    func sayHi(msg: String){
        print("\(msg) \(name)")
    }
}
let tom = User("tom", 23)
// tom.sayHi()
tom.sayHi(msg: "hola")

classの継承

class User {
    let name: String // property
    var score: Int
    init(_ name: String,_ score: Int){
        self.name = name
        self.score = score
    }
    func sayHi(){
        print("hi \(name)")
    }
}

class AdminUser: User {
    func sayHello(){
        print("hello \(name)")
    }
    override func sayHi(){
        print("[admin] hi \(name)")
    }
}
let tom = User("tom", 23)
let bob = AdminUser("bob", 33)
print(bob.name)
print(bob.score)
bob.sayHi()
bob.sayHello()
class User {
    let name: String // property
    var score: Int
    static var count = 0
    init(_ name: String,_ score: Int){
        self.name = name
        self.score = score
        User.count += 1
    }
    func sayHi(){
        print("hi \(name)")
    }
    static func getInfo(){
        print("\(count) instances")
    }
}

User.getInfo()
let tom = User("tom", 23)
User.getInfo()

型キャスト

// asを使った変換 -> 型キャスト
class User {
    let name: String // property
    init(_ name: String){
        self.name = name
    }
}
class AdminUser: User {}

let tom = User("tom")
let bob = AdminUser("bob")

let users: [User] = [tom, bob]

for user in users {
    // if let u = user as? AdminUser{
    //     print(u.name)
    // }
    if user is AdminUser {
        user as! AdminUser
        print(u.name)
    }
}