import UIKit class ViewController: UIViewController { @IBOutlet weak var timerLabel: UILabel! var startTime: TimeInterval? = nil var timer = Timer() var elapsedTime: Double = 0.0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } setButtonEnabled(start: true, stop: flase, reset: false){ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setButtonEnabled(start: Bool, stop: Bool, reset: Bool){ self.startButton.isEnabled = start self.stopButton.isEnabled = stop self.resetButton.isEnabled = reset } @objc func update(){ // print(Date.timeIntervalSinceReferenceDate) if let startTime = self.startTime { let t: Double = Date.timeIntervalSinceReferenceDate - startTime + self.elapsedTime print(t) let min = Int(t / 60) let sec = Int(t) % 60 let msec = Int((t - Double(sec)) * 100.0) self.timerLabel.text = String(format: "%02d:%02d:%02d", min, sec, msec) } } @IBAction func startTimer(_ sender: Any) { self.startTime = Date.timeIntervalSinceReferenceDate self.timer = Timer.scheduledTimer( timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) } @IBAction func stopTimer(_ sender: Any) { if let startTime = self.startTime { self.elapsedTime += Date.timeIntervalSinceReferenceDate - startTime } self.timer.invalidate() } @IBAction func resetTimer(_ sender: Any) { self.startTime = nil self.timerLabel.text = "00:00:00" self.elapsedTime = 0.0 } }
Category: Swift / SwiftUI
class is not key value coding-compliant
[
はて?
いらない接続を解除すると消えるようだが、消えんぞ。
#selectorのerror
#selector(self.hoge)がエラーになる。
func update()を@objc func update()とするとエラーが解消してbuild出来る。
@objc func update(){ print(Date.timeIntervalSinceReferenceDate) } @IBAction func startTimer(_ sender: Any) { Timer.scheduledTimer( timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) } @IBAction func stopTimer(_ sender: Any) { } @IBAction func resetTimer(_ sender: Any) { }
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の立ちあがりが異常に遅いんだが。。。
あれ?
失敗してるーーーーーーーーーーーーーー
あ、いいのか
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) } }
swift fundamental
// var winners: Set<Int> = [3, 5, 8, 8] var winners: Set = [3, 5, 8, 8] print(winners)
// var winners: Set<Int> = [3, 5, 8, 8] var winners: Set = [3, 5, 8, 8] print(winners.contains(3)) winners.insert(10) winners.remove(5) print(winners) print(winners.count)
let a: Set = [1, 3, 5, 8] let b: Set = [3, 5, 8, 9] print(a.union(b)) print(a.intersection(b)) print(a.union(b)) print(a.subtracting(b))
辞書
// var sales: Dictionary<String, Int> = ["kobayashi":200, "kudo":300] // var sales = ["kobayashi": 200, "kudo": 300] // sales["kudo"] = 500 // print(sales["kobayashi"] ?? "n.a.") // sales["yushima"] = 400 // print(sales.count) // for(key, value) in sales { // print("\(key): \(value)") // } let d = [String: Int]() print(d.isEmpty) [/code 関数 // func sayHi(){ // print("hi") // } // sayHi() func sayHi()-> String{ return "hi" } print(sayHi())
// func sayHi(){ // print("hi") // } // sayHi() // func sayHi(name: String){ // print("hi \(name)") // } // sayHi(name: "tom") // func sayHi(from name: String){ // print("hi \(name)") // } // sayHi(from: "tom") // func sayHi(_ name: String){ // print("hi \(name)") // } // sayHi("tom") func sayHi(_ name: String = "tom"){ print("hi \(name)") } sayHi()
func add10(x: inout Int){ x = x + 10 print(x) } var i = 10 add10(x: &i)
class
class User { let name: String // property var score: Int init(){ self.name = "me!" self.score = 23 } } // let uer: User = User() let user = User() print(user.name) print(user.score) user.score = 26 print(user.score)