LoginSignup
24
22

More than 5 years have passed since last update.

サラバ! prepareForSegue

Last updated at Posted at 2016-04-20

SegueAddition

SegueAdditionというライブラリを書きました。

このライブラリはperformSegueWithIdentifierを便利に使えるようにしたものです。
使い方を見てみましょう。

let customString = "CustomString"
performSegue("SegueIdentfiier") { segue in
    guard let toViewController = segue.destinationViewController as? CustomViewController
        else {
            fatalError()
    }
    toViewController.string = customString
}

UIViewControllerのメソッドにperformSegueというメソッドを一つ追加しました。
performSegueは従来通りUIStoryboardSegue#identifierを引数に渡せば画面遷移をしてくれます。

performSegueWithIdentifierを使った下記のコードと一緒な動作をします。

...
let customString = "CustomString"
performSegueWithIdentifier("SegueIdentfiier", sender: customString)
...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    guard let toViewController = segue.destinationViewController as? CustomViewController,
              customString = sender as? String
          where segue.identifier == "SegueIdentfiier"
          else {
              fatalError() 
     }
     toViewController.string = customString
}

performSegueWithIdentifier と違う点は大きく二つです。

  • prepareForSegueが呼ばれません。
  • performSegueには(UIStoryboardSegue -> Void)?closureを引数として渡すことができます。 prepareForSegueでやろうとしていたことをclosureの中に書くことができます。

いかがでしょうか?
従来通りのperformSegueWithIdentifier, prepareForSegueで書く場合は、
遷移を命令する場所と準備を行う場所が乖離しており、書くのも読むのも大変でした。
また、senderでAnyObjectを渡せると言ってもprepareForSegue中でキャストしたり、
二つ以上の引数を渡したい場合はタプルを使用するなどが必要だったのではないでしょうか?

SegueAddition では、performSegueを使用することで従来通りの方法よりも書きやすさ読みやすさを実現しています。ViewControllerへ値を渡したい場合でもclosureの中に含めることによって柔軟に値を渡すことができます。

そして、SegueAddtionを導入したからといってperformSegueWithIdentifierprepareForSegueのペアが使えなくなるわけではありません。もちろん、ActionSegueも使えます。
ですので、以前からあるコードを変える必要はないです。

中身はとてもシンプルなので見てもらうと分かりますが、
循環参照もしない作りになっています。

Segueを使ってアプリ開発をしている方は是非おためしください。

おまけ

ResourceKitというライブラリを書いています。
このSegueAdditionを書き終わった時にTODOを一つ増やしました。

ResourceKitSegueAdditionのような書き方をサポートしようかなと思案中です。

let customString = "CustomString"
performSegueOpen() { segue in
    guard let toViewController = segue.destinationViewController as? CustomViewController else {
      fatalError()
    }
    toViewController.string = customString
}

これでwithIdentifierも消えてよりスッキリしそうです。

ResourceKitはこちらの記事で紹介しています。
まだハードコードで消耗してるの? ResourceKitで安全コーディング!
こちらの方も是非ごらんください。

\(^o^)/

24
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
22