クラス一つ一つに同じ処理を書くのは冗長なので、デリゲートを利用する。
AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
func getValue(key: String) -> String {
if key == "key1" {
return "value1"
} else if key == "key2" {
return "value2"
}
return ""
}
}
FirstViewController.swift
import UIKit
class FirstViewController: UIViewController {
let myDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
...
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let value = myDelegate.getValue("key1")
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
let myDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
...
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let value = myDelegate.getValue("key2")
}
}