Created
June 21, 2018 11:21
-
-
Save niwatako/c60b7cdd80abaa91f61495dfaee49afa to your computer and use it in GitHub Desktop.
enum as Option #CodePiece #potatotips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| potatotips #52 (iOS/Android開発Tips共有会) - connpass | |
| https://potatotips.connpass.com/event/88164/ | |
| ## r_plus あーる enum as Option iOS @r_plus | |
| オプションについて。いわゆるファンクションやメソッドの振る舞いをちょっと変えるときのオプション。 | |
| Boolが一番簡単ですね。SwiftにはOptionSetというプロトコルがあって、bitごとにオプションを割り当ててオプションSetの表現ができる。 | |
| Foundationでもよく使われていますね、DispatchQueueのフラグとか。 | |
| struct ShippingOptions { | |
| let rawValue | |
| static let hogeOption = ShippingOptions(rawValue: 1 << 0) | |
| } | |
| 使うときは | |
| 引数optionに配列でセットを渡す [ShippingOptions.xxx, ...] | |
| func doSomething(option: ShippingOptions) | |
| なんかオプション判定したいだけなのに記述が面倒じゃないか | |
| enum でいいんじゃないか | |
| 可変長引数を使ってVariadic Parameters | |
| ``` | |
| doSomething(arg, .nextDay, .priority) | |
| func doSomething(_ arg: Any, option: ShippingOptions...) | |
| ``` | |
| 実装側にはArrayが来ることに変わりは無いので変更なし。 | |
| 複雑な計算処理をしたいときはOptionSetのほうがいいかもしれないが、 | |
| ちょっとパターン用意したいだけなら面倒だと思う。 | |
| 単純なenumと可変長引数もありではないか。 | |
| OptionSetのすごい良いところがあれば教えてください |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment