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)
}
}