4
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

解決できるかもしれないエラー

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()
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
4
Help us understand the problem. What are the problem?