swiftuiuicolorcgcolor

SwiftUI: The compiler is unable to type-check this expression in reasonable time


I want to get the calendar color from EKEvent. But i´m getting the Error: The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions The Rectangle().fill causes the Error. How do i get the UIColor from calendar.cgcolor for the Rectangle?

           ForEach(0..<data.eventsByDay.prefix(4).count)
            {(section) in
              
                HStack(alignment: .bottom){
                    ForEach(0..<data.eventsByDay[section].prefix(3).count)
                    {(row) in
                        
                        Rectangle().fill(UIColor(cgcgolor: data.eventsByDay[section][row].calendar.cgcolor))
                        .frame(width: 3, height: 26, alignment: .leading)
                        .cornerRadius(1.5)
                        .padding(.bottom, 1.0)
                    }
             }

Solution

  • This error occurs when Xcode cannot determine the exact cause of the error.

    I suggest you the following instruction from the error

    try breaking up the expression into distinct sub-expressions

    You can do that by moving part of your view into a separate function or View, but also you can comment out blocks one by one until you see the actual error or until it builds: in this case, the error is on one of the commented lines.


    In his case, you can comment out both ForEachs and replace them with constants:

    //ForEach(0..<data.eventsByDay.prefix(4).count)
    //{(section) in
        let section = 0
        HStack(alignment: .bottom){
    //        ForEach(0..<data.eventsByDay[section].prefix(3).count)
    //        {(row) in
                let row = 0
                Rectangle().fill(UIColor(cgcgolor: data.eventsByDay[section][row].calendar.cgcolor))
                    .frame(width: 3, height: 26, alignment: .leading)
                    .cornerRadius(1.5)
                    .padding(.bottom, 1.0)
            }
        }
    }
    

    Then Xcode will be able to tell you that you've made a typo in the UIColor initializer(cgColor instead of cgcgolor), and that fill takes Color instead of UIColor - second one is from UIKit and with SwiftUI it will almost never will be needed.

    So fixed variant looks like:

    ForEach(0..<data.eventsByDay.prefix(4).count)
    {(section) in
        let section = 0
        HStack(alignment: .bottom){
            ForEach(0..<data.eventsByDay[section].prefix(3).count)
            {(row) in
                let row = 0
                Rectangle().fill(Color(data.eventsByDay[section][row].calendar.cgcolor))
                    .frame(width: 3, height: 26, alignment: .leading)
                    .cornerRadius(1.5)
                    .padding(.bottom, 1.0)
            }
        }
    }