Enum の switch self がとても便利
Swift2, Xcode7
enum の switch self を使った変数の設定がとても分かりやすく便利でした。以下の例はアプリ内の WebView で表示するアプリのタイトルと URL を enum で定義した例になります。WebView は色々な箇所から呼び出されることが多いので requestURL と title を受け取って表示するようにしています。
以下のように定義しておけば WebViewItem.GuideLine.requestURL
や WebViewItem.GuideLine.title
といった形で情報にアクセスできるので Xcode の補完も効いてとても便利です。
enum WebViewItem { case GuideLine case PersonalInformation case TeamsOfUse case FAQ var requestURL: NSURL { switch self { case .GuideLine: return NSURL(string: "https://example.com/guideline")! case .PersonalInformation: return NSURL(string: "https://example.com/personal_information")! case .TeamsOfUse: return NSURL(string: "https://example.com/terms_of_service")! case .FAQ: return NSURL(string: "https://example.com/faq")! } } var title: String { switch self { case .GuideLine: return "使い方のガイドライン" case .PersonalInformation: return "個人情報の取扱いについて" case .TeamsOfUse: return "利用規約" case .FAQ: return "よくある質問" } } }