LoginSignup
0
1

More than 3 years have passed since last update.

enumを使ってリテラルをまとめる

Last updated at Posted at 2020-09-21

こんにちは。
最近自分が書いているCodeの品質を上げるために日々模索中です。
最近よく思うのは stringの文言とか、identifierを直書きしたりとか、そういうのしたくないなと思うようになり、
良い書き方ないかなと考えてCode読みあさって考えてみたら良さげな実装を思いついたので、記事にしようと思いました。

結論

enumで定義してしまえばまとまっててわかりやすいんじゃね?

よくある実装1

  • UITableViewのidentifierとか
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
    /// ...
    return cell

よくある実装2

private let cellId = "hogeCell"
/// ...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TableViewCell
    /// ...
    return cell

上記のよな感じで実装するとなんかいけてないし、個人的に直書きしたくないので(よきせぬ不具合を出したくない)ので以下の実装にしてみました。

実装

enum IdentifierType {
    static let segueId = "hogeSegue"
    static let cellId = "fugaCell"
    static let nibId = "HogeFugaTableViewCell"
   }

こんな感じで定義して、

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: IdentifierType.fugaCell, for: indexPath) as! TableViewCell
    /// ...
    return cell

とか

let nib = UINib(nibName: IdentifierType.nibId, bundle: nil)
hogeTableView.register(nib, forCellReuseIdentifier: IdentifierType.cellId)

みたいにして定義してあげれば、どこの何が定義してあるのかとてもわかりやすいし、直書きしなくてより安全なのではと思いこのような実装にしてみました。

まとめ

今回は、さくっとできてそれなりにまとめられて、すっきりできて、より安全に、より可読性も上がるなと個人的に思い上記の実装をしてみました。

しかし、より大規模アプリとかになると上記のような実装だけだといろいろ足りないし、より広範囲でまるっとサポートしてくれたらと思うので、より安全性や品質を高めて行ったり、楽したかったりしたらR.swiftがとても優秀なのでそれ使った方が良いと思います。
あくまで上記は小規模アプリとかで、ライブラリ入れなくても良いくらいの規模感のアプリなら、上記で対応しても良さそうに思いました。

読んでいただきありがとうございました!
もっと良い実装とか他何かありましたらコメントいただけたら涙が出るくらい喜びます!!

0
1
0

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
0
1