最近剛到新公司,這裡的專案大量的使用Storyboard,在前公司時,因為多人協作的關係,並沒有使用Storyboard 在進行開發,因此,結合了一些已閱讀過的觀念,順便來實作看看。
原本的問題
原本使用Storyboard 要拿到一個viewController 的instance 時,需要像這樣:
func foo() {
let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
let initViewController = storyboard.instantiateInitialViewController()
let viewController = storyboard.instantiateViewController(withIdentifier: "AnIdentifierForViewController") as! ViewController
// Do something...
}
這邊有幾個缺點:
- Storyboard 與ViewController 的Identifier 都是字串,重複使用時容易typo,對開發來說造成許多變因,以經驗上來說挺危險的
- 使用了
as!
來做downcast,但不使用強制轉型又顯得哆嗦