個人的にobj-cからswiftの目立つ変化はヘッダファイルがないことと「#pragma mark」がないことでした。(見た目だけでの話ですが。。)
もちろん、コーディングのパラダイム(Functional programming)のような重要な変化はありますが、まだ勉強不足で後ほど書こうと思っています。
ます今回は、swift的にコードを書くコードスタイルを現場の先輩からいろいろアドバイスをいただいたので紹介したいと思います。
基本的なクラス内のプロパティ、メソッドの配置などを書いてみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import UIKit // MARK: - Enum private enum Hoge { case HogeA, HogeB, Count } private enum Huga { case HugaA, HugaB, Count } //継承を避けるため、finalをつけておく。 final class SomeViewController: UIViewController { // MARK: - Properties //あれば定義しておく // MARK: - IBOutlets @IBOutlet weak var tableView: UITableView! // MARK: - IBActions @IBAction private func switchAction(_ sender: UISwitch) { // } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } // MARK: - Internal Methods internal func someMethod() -> BOOL { // return true; } } //デリゲートなどはExtensionにまとめる // MARK: - Extensions extension SomeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let sectionHeight = CGFloat(20.0) return sectionHeight } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // } } extension SomeViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return Hoge.Count.hashValue } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { return Huga.Count.hashValue } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // } } |
この投稿へのコメント