1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftのComputed PropertiesはFunction内でも宣言できる

Last updated at Posted at 2022-07-02

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(Action.fetchListResponse)

    case let .fetchListResponse(.success(entity)):
        ...
        state.cursor = entity.cursor
        return .none

    case .rowOnAppear:
        ...
        return environment.userRepository  // 全く同じコードがあちこちに...
            .fetchList(cursor: state.cursor)
            .catchToEffect(Action.fetchListResponse)

でも、Computed Propertiesを使うとfetchListを書くだけでよくなるので、コードがスッキリします。

switch action {
    var fetchList: Effect<Action, Never> {
        environment.userRepository
            .fetchList(cursor: state.cursor)
            .catchToEffect(Action.fetchListResponse)
    }

    case .onAppear:
        ...
        state.cursor = nil
        return fetchList  // これだけでOK

    case let .fetchListResponse(.success(entity)):
        ...
        state.cursor = entity.cursor
        return .none

    case .rowOnAppear:
        ...
        return fetchList  // これだけでOK

...Functionでも良いんですけどね。

switch action {
    func fetchList() -> Effect<Action, Never> {
        environment.userRepository
            .fetchList(cursor: state.cursor)
            .catchToEffect(Action.fetchListResponse)
    }

    case .onAppear:
        ...
        state.cursor = nil
        return fetchList()  // これだけでOK

    case let .fetchListResponse(.success(entity)):
        ...
        state.cursor = entity.cursor
        return .none

    case .rowOnAppear:
        ...
        return fetchList()  // これだけでOK
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?