Hello
I get errors in ForEach that I don't know how to solve:
Generic struct 'ForEach' requires that 'Main' conform to 'RandomAccessCollection'
Unable to infer type of a closure parameter 'user' in the current context
Error at line 30 - 31
Code:
//
// ContentView.swift
// ARWeather
//
// Created by Jad Taljabini on 08/04/21.
//
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject var networkController: NetworkControllerItalia
var body: some View {
NavigationView {
Form{
TextField("Input city name", text: $networkController.cityName, onEditingChanged: { te_xt in
networkController.url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(networkController.cityName)&appid=") ?? URL(string: "https://www.apple.com")!
networkController.fun()
}, onCommit: {
withAnimation{
networkController.url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(networkController.cityName)&appid=") ?? URL(string: "https://www.apple.com")!
networkController.fun()
}
})
Section {
ForEach(networkController.users.weather ?? [], id: \.self){ user in
Text(user.main ?? "")
}
ForEach(networkController.users.main ?? Main(temp: 0), id: \.self){ user in
Text("\(user.temp)")
}
}
}
}
}
}
class NetworkControllerItalia: ObservableObject {
private var can: AnyCancellable?
@Published var cityName: String = ""
@Published var users = UserItalia(weather: [])
var url = URL(string: "https://www.apple.com")!
func fun(){
self.can = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: UserItalia.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {completion in
print(completion)
}, receiveValue: { users in
self.users = users
})
}//Funzione che riempe users di dati da internet
}
struct UserItalia: Decodable, Hashable{
var weather: [Weather]?
var main: Main?
}
struct Weather: Decodable, Hashable {
var main: String?
}
struct Main: Decodable, Hashable {
var temp: Float
}
The JSON API is like this:
{
"coord": {
"lon": -0.1257,
"lat": 51.5085
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 285.45,
"feels_like": 283.96,
"temp_min": 284.82,
"temp_max": 285.93,
"pressure": 1021,
"humidity": 47
},
"visibility": 10000,
"wind": {
"speed": 5.66,
"deg": 220
},
"clouds": {
"all": 20
},
"dt": 1617888145,
"sys": {
"type": 1,
"id": 1414,
"country": "GB",
"sunrise": 1617859180,
"sunset": 1617907473
},
"timezone": 3600,
"id": 2643743,
"name": "London",
"cod": 200
}
Thank you
Post
Replies
Boosts
Views
Activity
Hello
I am getting a lot of errors in ForEach and I don't know why at all.
Here is the code:
The error is at line 12
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject var networkController: NetworkControllerItalia
var body: some View {
Form{
TextField("Input city name", text: $networkController.cityName)
Section {
ForEach(networkController.users.weather, id: \.self){ user in
}
}
}
}
}
class NetworkControllerItalia: ObservableObject {
private var can: AnyCancellable?
@Published var cityName: String = ""
@Published var users = [UserItalia(weather: Weather())]
init(cityName: String) {
self.cityName = cityName
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(cityName)&appid=")!
self.can = URLSession.shared.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: [UserItalia].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: {completion in
print(completion)
}, receiveValue: { users in
self.users = users
})
}
}
struct UserItalia: Decodable, Hashable{
var weather: Weather
}
struct Weather: Decodable, Hashable {
var main: String?
}
Thank you
Hello
Do you know why the comma in this calculator app isn't working:
import SwiftUI
import Combine
enum Nums: String{
case uno = "1"
case due = "2"
case tre = "3"
case quattro = "4"
case cinque = "5"
case sei = "6"
case sette = "7"
case otto = "8"
case nove = "9"
case zero = "0"
case moltiplicazione = "X"
case divisione = "/"
case somma = "+"
case meno = "-"
case uguale = "="
case AC = "AC"
case piùMeno = "±"
case percentuale = "%"
case virgola = "."
case niente = ""
}
struct ContentView: View {
var numeri: [[Nums]] = [
[Nums.AC, Nums.piùMeno, Nums.percentuale, Nums.divisione],
[Nums.sette, Nums.otto, Nums.nove, Nums.moltiplicazione],
[Nums.quattro, Nums.cinque, Nums.sei, Nums.meno],
[Nums.uno, Nums.due, Nums.tre, Nums.somma],
[Nums.zero, Nums.niente, Nums.virgola, Nums.uguale]
]
private var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
@State var previousVar: Double = 0
let timer = Timer.publish(every: 0.001, on: .main, in: .common).autoconnect()
@State var con: Int = 0
@State var final: Double = 0
@State var operat = Nums(rawValue: "")
@State var digits: String = "0"
var res: Double {
get {
//digits.hasSuffix(".") ? Double(digits.dropLast()) ?? 0.0 : Double(digits) ?? 0.0
digits.hasSuffix(".") ? Double(digits) ?? 0.0 : Double(digits) ?? 0.0
}
nonmutating set {
digits = String(format: "%.10g", newValue) //- May need better formatting
}
}
var body: some View {
VStack{
Spacer()
HStack{
Spacer()
Text("\(digits)")
.font(.system(size: 50))
.bold()
.padding()
}
Spacer()
LazyVGrid(columns: gridItemLayout, content: {
ForEach(0..5){ i in
ForEach(0..4){ j in
RoundedRectangle(cornerRadius: 35.0)
.foregroundColor(.orange)
.frame(width: 80, height: 80, alignment: .center)
.overlay(
Text("\(numeri[i][j].rawValue)")
.font(.largeTitle)
.foregroundColor(.black)
).onTapGesture {
switch numeri[i][j] {
case Nums.AC:
operat = Nums.AC;
res = 0
case Nums.uguale:
operat = Nums.uguale;
res = final
case Nums.somma:
operat = Nums.somma;
previousVar = res;
res = 0;
con = 0
case Nums.meno:
operat = Nums.meno;
previousVar = res;
res = 0
con = 0
case Nums.divisione:
operat = Nums.divisione;
previousVar = res;
res = 0;
con = 0
case Nums.moltiplicazione:
operat = Nums.moltiplicazione;
previousVar = res;
res = 0;
con = 0
case Nums.percentuale:
operat = Nums.percentuale;
res = res / 100
case Nums.piùMeno:
operat = Nums.piùMeno;
if digits.hasPrefix("-") {
digits = String(digits.dropFirst())
} else {
digits = "-" + digits
}
con = 0
case Nums.virgola:
operat = Nums.virgola;
if !digits.contains(".") {
digits += "."
}
default:
if digits == "0" {
digits = numeri[i][j].rawValue
} else {
digits += numeri[i][j].rawValue
}
con += 1
}
}
}
}
}).onReceive(timer) { _ in
if con != 0 {
if operat == Nums.divisione{
final = previousVar / res
} else if operat == Nums.meno{
final = previousVar - res
} else if operat == Nums.moltiplicazione{
final = previousVar * res
} else if operat == Nums.somma{
final = previousVar + res
}
}
}
}.padding(2)
}
}
Maybe at line 51 and 52 or 121
(If you can explain my mistakes all around the code I would be grateful)
Thank you
Hello
Is there a way to append a number to a Double, like this:
var num: Double = 1
var num2 = num.append(1)
//num2 should be 11
Thank you
Hello, Is there a way to use "switch statement" inside of a NavigationLink Destination?
Example:
NavigationLink(destination:
switch i {
case 0: MatematicaView()
case 1: ArteView()
default: EmptyView()
}){
Text("Hello")
}
(The views are different, that's why I don't put them in one struct)
Thank you
Hello
How do I solve the Index out of range at line 81
I tried many ways, but none of them worked
//
// 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] = []
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
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
}, 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)")
}
}
}.onReceive(timer) { input in
voti2 = tutto()
}
.navigationTitle("Media")
}
}
func tutto() - [Float] {
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[con] += 0.5
}
con = con + 1
if con = testInt {
con = 0
}
}
}
return voti2
}
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)
}
}
Thank you very much
Hello
Is there any way to put the 2 Texts in an HStack without putting the 2 ForEachs together?
Code:
ForEach(model.data, id: \.objectID){ obj in
Text(model.getValue(obj: obj))
}.onDelete(perform: model.deleteData)
ForEach(date.data, id: \.objectID){ obj1 in
Text("\(date.getValue(obj: obj1), formatter: dateFormatter)")
}.onDelete(perform: date.deleteData)
Thank you
Hello
Does anyone know how to use real time image recognition in SwiftUI with a Create ML model.
Thank you
Hello
I'm trying to detect objects with CreateML, but it gives me this warning that I think is breaking my app:
'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately.
The classfier.model is a CreatML model that has some images
Have any ideas on how to fix it?
import UIKit
import AVKit
import Vision
import CoreML
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
		
		let identifierLabel: UILabel = {
				let label = UILabel()
				label.backgroundColor = .white
				label.textAlignment = .center
				label.translatesAutoresizingMaskIntoConstraints = false
				return label
		}()
		override func viewDidLoad() {
				super.viewDidLoad()
				
				// here is where we start up the camera
				// for more details visit: https://www.letsbuildthatapp.com/course_video?id=1252
				let captureSession = AVCaptureSession()
				captureSession.sessionPreset = .photo
				
				guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
				guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
				captureSession.addInput(input)
				
				captureSession.startRunning()
				
				let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
				view.layer.addSublayer(previewLayer)
				previewLayer.frame = view.frame
				
				let dataOutput = AVCaptureVideoDataOutput()
				dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
				captureSession.addOutput(dataOutput)
				
				
				
				setupIdentifierConfidenceLabel()
		}
		
		fileprivate func setupIdentifierConfidenceLabel() {
				view.addSubview(identifierLabel)
				identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32).isActive = true
				identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
				identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
				identifierLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
		}
		
		func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
//				print("Camera was able to capture a frame:", Date())
				
				guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
				
				// !!!Important
				// make sure to go download the models at https://developer.apple.com/machine-learning/ scroll to the bottom
				guard let model = try? VNCoreMLModel(for: Classfier().model) else { return }
				let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
						
						//perhaps check the err
						
//						print(finishedReq.results)
						
						guard let results = finishedReq.results as? [VNClassificationObservation] else { return }
						
						guard let firstObservation = results.first else { return }
						
						print(firstObservation.identifier, firstObservation.confidence)
						
						DispatchQueue.main.async {
								self.identifierLabel.text = "\(firstObservation.identifier) \(firstObservation.confidence * 100)"
						}
						
				}
				
				try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
		}
}
Thank you for your time
Hello
I'm trying to fetch some data from a JSON Api, but when I access the properties of my struct it tells me Value of Type "Name Of The Struct" has no member "name of the property"
Any idea on how to fix it
Code:
import SwiftUI
import Combine
struct ContentView: View {
		
		@ObservedObject var networkController = NetworkControllerItalia()
		var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
		
		var body: some View {
				NavigationView{
						ScrollView{
								ForEach(networkController.users, id: \.self){ user in
										GroupBox(label: Text(user.round ?? ""), content: {
												VStack{
														Text(user.team1 ?? "")
												}
										}).padding()
						}
						.navigationTitle("Serie A")
				}
		 }
	 }
}
class NetworkControllerItalia: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/it.1.json")!
		//let url = URL(string: "google.com")!
		@Published var users = [UserItalia(matches: [])]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [UserItalia].self, decoder: JSONDecoder())
						//.replaceError(with: [])
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveCompletion: {completion in
								print(completion)
						}, receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct UserItalia: Decodable, Hashable {
		var matches: [Matches]?
}
struct Matches: Decodable, Hashable {
		var round: String?
		var date: String?
		var team1: String?
		var team2: String?
}
Thank You
Hello
I made a custom Picker View but I don't have any idea on how to change the background color to grey when I press on one of the options
Here is the code:
struct PickerView: View {
		
		var arr: [String] = ["Easy", "Medium", "Hard"]
		var h: CGFloat = 50
		var w: CGFloat = 320
		
		@ObservedObject var input: UserInput
		var body: some View{
				HStack(spacing: 40){
						ForEach(0..<arr.count){ i in
								HStack(spacing: 25){
										Text(arr[i])
												.bold()
												.onTapGesture {
														switch i{
														case i: input.indi = i
														default: return
														}
														print(i)
												}
										if(i < arr.count - 1){
										Divider()
												.frame(height: 25)
										}
								}
						}
				}.padding()
				.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
				.overlay(
						RoundedRectangle(cornerRadius: 16)
								.stroke(Color.gray, lineWidth: 3)
				)
		}
}
class UserInput: ObservableObject {
		@Published var indi: Int = 0
}
Thank you for your time
Hello
I'm trying to use a formatter on a String but it is giving me this error
Cannot convert value of type 'String' to type 'NSNumber' in coercion, is there a simple and short way to fix it?
Here is the code
import SwiftUI
struct TemperatureView: View {
		
		@State private var inputValue = ""
		
		 let inputUnits = [
				"celsius [°C]",
				"kelvin [K]",
				"fahrenheit [°F]"
		]
		let outputUnits = [
				"celsius [°C]",
				"kelvin [K]",
				"fahrenheit [°F]"
	 ]
		@State private var inputUnitValue = 0
		
		@State private var outputUnitValue = 1
		
		
		var after: String{
				var input: Measurement<UnitTemperature>
				var output: String = ""
				
				switch inputUnits[inputUnitValue] {
				case "celsius [°C]": input = Measurement(value: Double(inputValue) ?? 0, unit: .celsius)
				case "kelvin [K]": input = Measurement(value: Double(inputValue) ?? 0, unit: .kelvin)
				case "fahrenheit [°F]": input = Measurement(value: Double(inputValue) ?? 0, unit: .fahrenheit)
				default: input = Measurement(value: Double(inputValue) ?? 0, unit: UnitTemperature.celsius)
				}
				switch outputUnits[outputUnitValue] {
				case "celsius [°C]": output = outputFormatter.string(from: input.converted(to: .celsius))
				case "kelvin [K]": output = outputFormatter.string(from: input.converted(to: .kelvin))
				case "fahrenheit [°F]": output = outputFormatter.string(from: input.converted(to: .fahrenheit))
				default: output = String(describing: input.converted(to: UnitTemperature.celsius))
						
				}
						
				return output
		}
		
		@Environment(\.presentationMode) var presentationMode
		let outputFormatter: MeasurementFormatter = {
						let nf = NumberFormatter()
						nf.locale = Locale.current
						nf.usesSignificantDigits = true
						let mf = MeasurementFormatter()
						mf.numberFormatter = nf
						mf.unitOptions = .providedUnit
						return mf
				}()
				
		var body: some View {
				NavigationView{
						Form{
								Section(header: Text("Enter your Input value")){
												TextField("Have a goal?", text: $inputValue)
														.keyboardType(.decimalPad)
								}
								
								Section(header: Text("Input")){
										Picker("Input values", selection: $inputUnitValue){
												ForEach(0..<inputUnits.count){ item in
														Text(inputUnits[item])
												}
										}
								}
								
								Section(header: Text("Output")){
										Picker("Output values", selection: $outputUnitValue){
												ForEach(0..<outputUnits.count){ item in
														Text(outputUnits[item])
												}
										}
								}
								
								Section(header: Text("Check your Output value")){
										Text("\(after as NSNumber, formatter: outputFormatter)")
								}
								
						}
						.navigationBarTitle("Temperature")
						.navigationBarItems(trailing:
																		Button(action: {
																				presentationMode.wrappedValue.dismiss()
																		}) {
																				Image(systemName: "xmark").font(.title).foregroundColor(.blue)
																		}
						)
				}
		}
		
}
The error is at line 80/81
Thank you for your time
Hello
Everytime I run a project I get this popup: The document “iosfwd” could not be saved. You don’t have permission.
How do I fix it?
Thank you
Hello
I'm using Measurement(...) to convert watts to femtowatts, but if I convert 1 watts to femtowatts I get 999999999999999.9 instead of 1e+15, I have no idea on how to fix it, any help or ideas, here is the code
:
import SwiftUI
struct PowerView: View {
		
		@State private var inputValue = ""
		
		 let inputUnits = [
				"watts",
				"femtowatts"
		]
		let outputUnits = [
				"watts",
				"femtowatts"
	 ]
		@State private var inputUnitValue = 0
		
		@State private var outputUnitValue = 1
		
		var after: String{
				var input = Measurement(value: 0, unit: UnitPower.watts)
				var output: String = ""
				
				switch inputUnits[inputUnitValue] {
				case "watts": input = Measurement(value: Double(inputValue) ?? 0, unit: UnitPower.watts)
				case "femtowatts": input = Measurement(value: Double(inputValue) ?? 0, unit: UnitPower.femtowatts)
				default: input = Measurement(value: Double(inputValue) ?? 0, unit: UnitPower.watts)
				}
				switch outputUnits[outputUnitValue] {
				case "watts": output = String(describing: input.converted(to: UnitPower.watts))
				case "femtowatts": output = String(describing: input.converted(to: UnitPower.femtowatts))
				default: output = String(describing: input.converted(to: UnitPower.watts))
						
				}
						
				return output
		}
		
				
		var body: some View {
				NavigationView{
						Form{
								Section(header: Text("Enter your Input value")){
												TextField("Have a goal?", text: $inputValue)
								}
								
								Section(header: Text("Input")){
										Picker("Input values", selection: $inputUnitValue){						 	 ForEach(0..<inputUnits.count){ item in
														Text(inputUnits[item])
												}
										}
								}
								
								Section(header: Text("Output")){
										Picker("Output values", selection: $outputUnitValue){
												ForEach(0..<outputUnits.count){ item in
														Text(outputUnits[item])
												}
										}
								}
								
								Section(header: Text("Check your Output value")){
										Text("\(after)")
								}
								
						}
						.navigationBarTitle("Pressure")
				}
		}
		
}
Thank you for your time
(Is there a way to use NumberFormatter with the computed String)
Hello
Is there a way to dismiss a decimal Keyboard by tapping (anywhere) on the screen (without putting .onTapGesture {hideKeyboard()} on the NavigationView)
Thank you