UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Problem chaining with ternary

Forums > 100 Days of SwiftUI

Test for playgrounds

import Cocoa

let a = 5

print(a > 5 ? 1 : (a < 5 ? 9 : 2))

works as expected

now in swiftui to solve Iexpense challenge

//
//  ContentView.swift
//  Project7
//
//  Created by Paul Hudson on 17/02/2020.
//  Copyright © 2020 Paul Hudson. All rights reserved.
//

import SwiftUI

struct ExpenseItem: Identifiable, Codable {
    let id = UUID()
    let name: String
    let type: String
    let amount: Int
}

class Expenses: ObservableObject {
    @Published var items: [ExpenseItem] {
        didSet {
            let encoder = JSONEncoder()
            if let encoded = try? encoder.encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    init() {
        if let items = UserDefaults.standard.data(forKey: "Items") {
            let decoder = JSONDecoder()
            if let decoded = try? decoder.decode([ExpenseItem].self, from: items) {
                self.items = decoded
                return
            }
        }

        self.items = []
    }
}

struct ContentView: View {
    @ObservedObject var expenses = Expenses()
    @State private var showingAddExpense = false

    var body: some View {
        NavigationView {
            List {
                ForEach(expenses.items) { item in
                    HStack {
                        VStack(alignment: .leading) {
                            Text(item.name)
                                .font(.headline)
                            Text(item.type)
                        }

                        Spacer()
                        Text("$\(item.amount)")
                    }
                    .foregroundColor(item.amount < 10 ? .red : (item.amount < 100 ? .blue : .black)) // same chaining here but compiler cant compile throughs error that it takes too much time to compile.

                }
                .onDelete(perform: removeItems)
            }
            .navigationBarTitle("iExpense")
            .navigationBarItems(leading: EditButton(),trailing:
                Button(action: {
                    self.showingAddExpense = true
                }) {
                    Image(systemName: "plus")
                }
            )
            .sheet(isPresented: $showingAddExpense) {
                AddView(expenses: self.expenses)
            }
        }
    }

    func removeItems(at offsets: IndexSet) {
        expenses.items.remove(atOffsets: offsets)
    }

    func styling (for: Int)
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

error: The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

if I will reduce conditions of ternery to 1 if else block i.e. condition ? statement : statement . then it will compile and run as it should

Solved with adding new modifier but still cant understand why ternery doesnt want to work.

struct fontStyling: ViewModifier{
    var amount:Int

    func body(content: Content) -> some View {

        var color = Color.black

        if amount < 10 {
            color = Color.blue
        }

        else if amount < 100 {
            color = Color.green
        }

        else if amount < 1000 {
            color  = Color.yellow
        }

        return content
        .foregroundColor(color)
    }
}

2      

I was going to suggest replacing .red with Color.red, etc. Maybe trying to figure out the data type there has caused the delay.

2      

tried with Color.red didnt help same error.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.