13
5

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 3 years have passed since last update.

SwiftUIで「式が複雑すぎる」「式を分解しろ」と言われたら

Last updated at Posted at 2020-05-16

##解決できるかもしれないエラー
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

このエラーによく遭遇するのですが、具体的な解決法が分からず毎度苦戦します。fizzbuzzのような2つの条件を扱おうとするだけでも出現するエラーです。とても厄介。ここでは一つの解決策を共有できればと思います。参考

##エラー例

import SwiftUI

struct test: View {
    var body: some View {
        List(0..<100) { number in
            if number % 3 == 0 || number % 5 == 0 {
                Text("number\(number) は3または5の倍数")
            } else {
                Text("number\(number)3と5の倍数のいずれでもない")
            }
        }
    }
}

struct escape_Previews: PreviewProvider {
    static var previews: some View {
        test()
    }
}

if number % 3 == 0 || number % 5 == 0に問題があるようです。複雑というよりも、処理が一度に複数あるイメージでしょうか。
解決するために,if number % 3 == 0 || number % 5 == 0を関数にします。

import SwiftUI

struct escape: View {
    func check(number: Int) -> Bool {
        number % 3 == 0 || number % 5 == 0
    }
    var body: some View {
        
        List(0..<100) { number in
            if self.check(number: number){
                Text("number\(number) は3または5の倍数")
            } else {
                Text("number\(number)3と5の倍数のいずれでもない")
            }
        }
    }
}

struct escape_Previews: PreviewProvider {
    static var previews: some View {
        escape()
    }
}
13
5
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
13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?