I changed it to this, but when I press Add, the simulator freezes
//
// ContentView.swift
// Fede
//
// Created by Jad Taljabini on 14/03/21.
//
import SwiftUI
struct ContentView: View {
@State private var media: String = ""
@State private var voto: String = ""
@State private var voti: [Float] = []
@State private var nVoti: Int = 0
@State private var test: String = ""
@State private var voti2: [Float] = []
var body: some View {
NavigationView {
Form {
Section{
TextField("A che media vuoi arrivare", text: $media)
}
Section{
TextField("Quanti voti prenderai", text: $test)
}
Section{
HStack {
TextField("Tuoi voti", text: $voto)
Spacer()
Button(action: {
voti.append(Float(voto) ?? 0)
voto = ""
nVoti = nVoti + 1
tutto()
}, label: {
Text("Add")
})
}
}
Section{
ForEach(voti, id: \.self){ item in
Text("\(item, specifier: "%.1f")")
}.onDelete(perform: removeRows)
}
Section(header: Text("Voti che devi prendere")){
ForEach(voti2, id: \.self){ item2 in
Text("\(item2)")
}
}
}
.navigationTitle("Media")
}
}
func tutto() {
let testInt = Int(test) ?? 0
let mediaFloat = Float(media) ?? 0
var mediaEffettiva = mediaEffFunzione(dim: nVoti)
if mediaEffettiva mediaFloat {
for i in 0..testInt - 2 {
voti2[i] = Float(Int(mediaEffettiva + 1))
}
let mediaEffettivaInt = Int(mediaEffettiva)
let mediaFloatInt = Int(mediaFloat)
var con: Int = 0
while(mediaEffettivaInt mediaFloatInt){
for j in nVoti..nVoti + testInt - 2{
voti[j] = voti2[j - nVoti];
}
mediaEffettiva = mediaEffFunzione(dim: nVoti + testInt)
if mediaEffettiva mediaFloat && voti2.isValidIndex(con) {
voti2[con] += 0.5
}
con = con + 1
if con = testInt {
con = 0
}
}
}
}
func removeRows(at offsets: IndexSet) {
voti.remove(atOffsets: offsets)
}
func mediaEffFunzione(dim: Int) - Float {
var somma: Float = 0
for i in voti{
somma = somma + i
}
return somma / Float(dim)
}
}
extension Array {
func isValidIndex(_ index: Int) - Bool {
return index = 0 && index self.count
}
}
Post
Replies
Boosts
Views
Activity
And your code revealed that if you define a combined entity, your code all things would be solved.
What do you mean with combined entity and how do I do it?
var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CoreDataModel")
container.loadPersistentStores(completionHandler: {(StoreDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges{
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
class dataModel: ObservableObject{
@Published var data: [NSManagedObject] = [] //Contiene i dati, tutti i favorites
@Published var txt = ""
let context = persistentContainer.viewContext
init() {
readData()
}
func readData(){
let request = NSFetchRequestNSFetchRequestResult(entityName: "Content")
do {
let results = try context.fetch(request)
self.data = results as! [NSManagedObject]
} catch {
print(error.localizedDescription)
}
}
func writeData(){
let entity = NSEntityDescription.insertNewObject(forEntityName: "Content", into: context)
entity.setValue(txt, forKey: "value")
do {
try context.save()
self.data.append(entity)
//txt = ""
} catch {
print(error.localizedDescription)
}
}
func deleteData(indexSet: IndexSet){
for index in indexSet{
do {
let obj = data[index]
context.delete(obj)
try context.save()
let index = data.firstIndex(of: obj)
data.remove(at: index!)
} catch {
print(error.localizedDescription)
}
}
}
func updateData(){
}
func getValue(obj: NSManagedObject) - String{
return obj.value(forKey: "value") as! String
}
}
class dataModel1: ObservableObject{
@Published var data: [NSManagedObject] = [] //Contiene i dati, tutti i favorites
@Published var dataAttuale = Date()
let context = persistentContainer.viewContext
init() {
readData()
}
func readData(){
let request = NSFetchRequestNSFetchRequestResult(entityName: "Content2")
do {
let results = try context.fetch(request)
self.data = results as! [NSManagedObject]
} catch {
print(error.localizedDescription)
}
}
func writeData(){
let entity = NSEntityDescription.insertNewObject(forEntityName: "Content2", into: context)
entity.setValue(dataAttuale, forKey: "date")
do {
try context.save()
self.data.append(entity)
//txt = ""
} catch {
print(error.localizedDescription)
}
}
func deleteData(indexSet: IndexSet){
for index in indexSet{
do {
let obj = data[index]
context.delete(obj)
try context.save()
let index = data.firstIndex(of: obj)
data.remove(at: index!)
} catch {
print(error.localizedDescription)
}
}
}
func updateData(){
}
func getValue(obj: NSManagedObject) - Date{
return obj.value(forKey: "date") as! Date
}
}
The getValue function returns two different types in the two classes, thats why I need two FoeEach loops
@ObservedObject var model = dataModel()
@ObservedObject var date = dataModel1()
dataModel and dataModel1 are two different classes which contain two different arrays.
The two classes have to be sperate.
The arrays have the same length because :
Button(action: {
model.writeData()
date.writeData()
}) {
Image(systemName: "plus")
}
model.writeData() saves the String that is in the TextFiled and date.writeData()saves the Date.
Thank you for your time, every thing is working
I have the last question, is it possible (in the same ForEach) to display score.ft ?
You need to understand better what your data structures are. Maybe it's because I started programming/developing few weeks ago.
It worked, Thank you very much
yes but now it gave me an error at line 13: Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'UserItalia' conform to 'RandomAccessCollection'
I tried to change \.self with name but it didn't work
I never used CodingKeys (I don't know what it's used for), but if it solves the problem I could include it
The JSON file is in the URL at line 28
It says Value of type UserItalia has no member team1.
I thought about this but in this way it would change the background of the entire RoundedRectangle and it's not what I want, but Thank you anyway
What I want is (for example) when I tap on the Text(arr[0]) at line 12 the background becomes grey and if I tap on Text(arr[1]), Text(arr[0]) returns to be normal background and Text(arr[1]) becomes grey
Hello
I'll show you what I did
class NetworkControllerItalia: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "apple.com")!
		@Published var users = [UserItalia()]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [UserItalia].self, decoder: JSONDecode
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveCompletion: {completion in
								print(completion)
						}, receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct UserItalia: Decodable, Hashable {
}
In the struct you put the properties that you will fetch from your JSON, and instead of apple.com at line 4 you have to put the URL from where you are getting the data, then in the the ContentView you should use a ForEach like this:
@ObservedObject var networkController = NetworkControllerItalia()
ForEach(networkController.users, id: \.self){ user in
Text(user.nameOfProperty)
	}
Have a nice day
Ok, Thank you for your time
The extension is for the $saveGoal.bound, because if i delete .bound it gives me errors
extension Optional where Wrapped == String {
		
		var _bound: String? {
				get{
						return self
						
				}
				set{
						self = newValue
						
				}
		}
		
		var bound: String {
				get{
						return _bound ?? ""
				}
				set {
						_bound = newValue.isEmpty ? nil : newValue
				}
		}
}
Yes SaveGoal is Optional