今まで知らなくて発見だったのでメモ。
SwiftのComputed PropertiesはFunction内でも宣言できます。
struct State { var foo = "foo" } var state = State() func testComputedProp() { var result: Bool { // ここにComputed Propertiesが宣言できる! someLogic(str: state.foo) } print(result) state.foo = "bar" print(result) } func someLogic(str: String) -> Bool { return str == "bar" } testComputedProp() // 以下の順で出力される // false // true
限定的な具体例になっちゃいますが、、
TCAのReducerを実装してるときに、同じデータ取得のコードをあちこちに書いていました。
switch action { case .onAppear: ... state.cursor = nil return environment.userRepository // 全く同じコードがあちこちに... .fetchList(cursor: state.cursor) .catchToEffect() .map(Action.fetchListResponse) case let .fetchListResponse(.success(entity)): ... state.cursor = entity.cursor return .none case .rowOnAppear: ... return environment.userRepository // 全く同じコードがあちこちに... .fetchList(cursor: state.cursor) .catchToEffect() .map(Action.fetchListResponse)
でも、Computed Propertiesを使うとfetchList
を書くだけでよくなるので、コードがスッキリします。
switch action { var fetchList: Effect<Action, Never> { environment.userRepository .fetchList(cursor: state.cursor) .catchToEffect() .map(Action.fetchListResponse) } case .onAppear: ... state.cursor = nil return fetchList case let .fetchListResponse(.success(entity)): ... state.cursor = entity.cursor return .none case .rowOnAppear: ... return fetchList