Post

Replies

Boosts

Views

Activity

Saving User Data to Array inside Struct
I'd like to properly save inputted user data /variables inside a array which is inside a struct but unable to get it to work. Currently, I have a few strucs: struct Household: Codable {     let id  = UUID()     var region: String     var householdSize: Int = 1     var receivingBenefits: [String]     var energyCrisis: Bool     var utilityProviders: [String]     var residenceType: String     var propertyTaxPastDue, homeNeedsRepairs, filedPreviousYearTaxReturn, heatingSystemNeedsRepairs: Bool     var atRiskOfHomelessness: Bool     var receivedMaximumBenefit: ReceivedMaximumBenefit     var personDetails: [PersonDetail]     var incomes: [Income]     var assets: [Asset]     enum CodingKeys: String, CodingKey {         case region         case householdSize = "household_size"         case receivingBenefits = "receiving_benefits"         case energyCrisis = "energy_crisis"         case utilityProviders = "utility_providers"         case residenceType = "residence_type"         case propertyTaxPastDue = "property_tax_past_due"         case homeNeedsRepairs = "home_needs_repairs"         case filedPreviousYearTaxReturn = "filed_previous_year_tax_return"         case heatingSystemNeedsRepairs = "heating_system_needs_repairs"         case atRiskOfHomelessness = "at_risk_of_homelessness"         case receivedMaximumBenefit = "received_maximum_benefit"         case personDetails = "person_details"         case incomes, assets     } } struct PersonDetail: Codable, Identifiable {     let id  = UUID()  // <-- here     var age: Int = 18     var maritalStatus: String = ""     var minimumEmploymentOverExtendedPeriod: Bool     var workStatus: String = ""     var pregnant: Bool     var attendingSchool: Bool = false     var disabled: Bool     enum CodingKeys: String, CodingKey {         case age         case maritalStatus = "marital_status"         case minimumEmploymentOverExtendedPeriod = "minimum_employment_over_extended_period"         case workStatus = "work_status"         case pregnant         case attendingSchool = "attending_school"         case disabled     } } class Base: ObservableObject, Codable {     @Published var household: Household     enum CodingKeys: String, CodingKey {         case household = "household"     } } Now, I can easily bind a Textfield, toggle or Picker to anything under the Household struct for example below which I believe is easily connected via household in the Base() class.. HStack() {       Image(systemName:"wrench.and.screwdriver.fill")                    .frame(width: 15, height: 15)       Toggle(isOn: $eligBase.household.homeNeedsRepairs) {                Text("Need Home Repairs?")                        .font(.system(size: 15))                   }.tint(.blue)               } However, I'm unable to connect anything in the array`[PersonDetail], which I included the struct. For example, If I wanted to connected a Toggle for the disabled variable in `PersonDetail', I get an error, here is my disabled toggle:  Toggle(isOn: $eligBase.household.personDetails.disabled) {               Text("Disabled")                         .font(.system(size: 15)) ...... } I receive an error stating: Value of type 'Binding<[PersonDetail]>' has no dynamic member 'disabled' using key path from root type '[PersonDetail]' Any ideas how I can connect Toggles, Textfield, Picker to a variable in an array which is in a struct? Thanks.
1
0
558
Mar ’22
Arrays in struct/class are not printing in console
Basically, what I want to do is print a full json object that has a number of arrays inside it. For the sake of simplicity, I'll just paste two of the structs below: struct Incomes : Codable {     var *****_monthly_amount: Int = 0     var countable_group: String = ""     var year: String = ""     enum CodingKeys: String, CodingKey {             case *****_monthly_amount         case countable_group         case year     } } struct Person_details :  Codable {     enum CodingKeys: CodingKey {         case age         case work_status, marital_status         case pregnant, disabled, attending_school, minimum_employment_over_extended_period     }      var age: Int = 18      var minimum_employment_over_extended_period: Bool = false      var work_status: String = ""      var pregnant: Bool = false      var attending_school: Bool = false      var disabled: Bool = false      var marital_status: String = "" } These two are connected to a struct: Household : struct Household :  Codable {      var receiving_benefits : [String] = []      var energy_crisis : Bool = false     var utility_providers: [String] = [""]     var person_details: [Person_details] = []     var Income: [Incomes] = []     enum CodingKeys: String, CodingKey {         case receiving_benefits = "receiving_benefits"         case energy_crisis = "energy_crisis"         case utility_providers = "utility_providers"         case person_details = "person_details"         case Income = "incomes"     } } Finally, a class that connects it all: class Json4Swift_Base : ObservableObject, Codable {     @Published var household = Household()     enum CodingKeys: String, CodingKey {         case household = "household"     }     init() { }     func encode(to encoder: Encoder) throws {         var container = encoder.container(keyedBy: CodingKeys.self)         try container.encode(household, forKey: .household)     }     required init(from decoder: Decoder) throws {         let container = try decoder.container(keyedBy: CodingKeys.self)         household = try container.decode(Household.self, forKey: .household)     } } Followed by a @StateObject & @State's:     @StateObject var Base = Json4Swift_Base()     @State var user = Household()     @State var personDetails = Person_details()     @State var Income1 = Incomes() When a button is selected, I have this to print out the json in the console:                 let encoder = JSONEncoder()                 encoder.outputFormatting = .prettyPrinted                 do {                     let data = try encoder.encode(Base)                     if let str = String(data: data, encoding: .utf8) {                         print("\(str)\n")                     }                 } catch {                     print("---> error: \(error)")                 }                  It prints this with Empty arrays: {   "household" : {     "assets" : [     ],     "person_details" : [     ],     "utility_providers" : [       ""     ],     "incomes" : [     ],     "receiving_benefits" : [     ],     "region" : "PA",     "residence_type" : "rent",     "received_maximum_benefit" : {       "cip" : false     },     "at_risk_of_homelessness" : false,     "property_tax_past_due" : false   } } When I print personDetails by itself and not Base, I get the person_details, but why can't I get person_details (or Income) when Base is printed (Since it's all connected) ? Why would it come up as an empty array? I have these values connected to toggles & TextFields but they're not printing. Thanks for any help!
2
0
1.1k
Mar ’22
Save/Print encoded data to Json (pretty printed)
Below, I have a codable class that I'm able to connect Published variables with the purpose of converting them to Json and sending an API (API is out of scope). I have these two variables connected in the app to a toggle and picker which I can print out the values print(user.age) etc.. when a button is pressed but.. now, I'd like a way to save this data in json format so I can print out both var's in json format (pretty printed) in the console when the button is pressed. Thanks! class User: ObservableObject, Codable {     enum CodingKeys: CodingKey {         case disabled case age     }     init() { }     required init(from decoder: Decoder) throws {         let container = try decoder.container(keyedBy: CodingKeys.self)         disabled = try container.decode(Bool.self, forKey: .disabled) age = try container.decode(Int.self, forKey: .age)     }     func encode(to encoder: Encoder) throws {         var container = encoder.container(keyedBy: CodingKeys.self)         try container.encode(disabled, forKey: .disabled) try container.encode(age, forKey: age)     }     @Published var disabled: Bool = false @Publisehd var age: Int = 18 }     @StateObject var user = User() // Connects to the Class.
1
0
2.2k
Mar ’22
Connect @State variables to a Codable struct
I currently have lots of @State var's on my app that I'd like to place inside a struct Codable which in turn will form the Json Object necessary to send as payload in an API. (The API part is out of scope for this question). My 'ask' is, how do I place variables like the 2 I have below, inside the codable struct so when selected a value from the user, those values will be saved in a Json object. For example, I have 2 variables:     @State var pregnant: Bool = false     @State var household_size: Int = 1 How will I place these two variables above in the codable struct?     struct Welcome: Codable {         let household: Household     }     struct Household: Codable {         var pregnant: String         var household_size: Int         enum CodingKeys: String, CodingKey {             case pregnant             case household_size } } Right now, I'm receiving an error when I try to let eligibility = Welcome(household: Household(pregnant: pregnant, household_size: household_size)) (Note the eligibility constant above are the values of the @State variable's in the App.) Thank you!
2
0
1.7k
Mar ’22
Converting Swift to JSON
I have a JSON object directly below that uses everything from Strings, Bools and Int's. This is an object I am trying to recreate in Xcode playground console. I'm currently having a difficult time recreating the person_details section of the object and I think because it's in brackets and has multiple values, like [String: Bool], [String: String] &amp; [String: Int] ? I posted towards the bottom what populates on the console, but any help structuring there person_details section in the would be great. You'll see below, in my let order, I'm structuring the data. If you need any additional info, please let me know. Thanks! let testJson = """ { "household": {     "region": "PA",     "household_size": 1,     "receiving_benefits": [     ],     "energy_crisis": false,     "utility_providers": [         "peco"     ],     "residence_type": "other",     "property_tax_past_due": false,     "home_needs_repairs": false,     "filed_previous_year_tax_return": false,     "heating_system_needs_repairs": false,     "at_risk_of_homelessness": false,     "received_maximum_benefit": {         "cip": false     },     "person_details": [         {             "age": 18,             "marital_status": "single",             "minimum_employment_over_extended_period": false,             "work_status": "recent_loss",             "pregnant": false,             "attending_school": false,             "disabled": false         }     ],     "incomes": [         {             "*****_monthly_amount": 700,             "countable_group": "household",             "year": "current"         },         {             "*****_monthly_amount": 700,             "countable_group": "household",             "year": "previous"         }     ],     "assets": [         {             "amount": 1000,             "countable_group": "household"         }     ] } } """ struct Eligibility: Encodable {     let residence: String     let hhmembers: Int     let receivingBen: [String]     let unhoused: Bool     let utilityType: [String]     let residenceType: String     let propertyTax: Bool     let homeRepairs: Bool     let fileLastTax: Bool     let heatRepairs: Bool     let receivingMax: [String: Bool]   //  let personDetails: [String]  //  let marital1: String   //  let age1: Int  //   let pregnant: Bool         enum CodingKeys: String, CodingKey {             case residence = "region"             case hhmembers = "household_size"             case receivingBen = "receiving_benefits"             case unhoused = "at_risk_of_homelessness"             case utilityType = "utility_providers"             case residenceType = "residence_type"             case propertyTax = "property_tax_past_due"             case homeRepairs = "home_needs_repairs"             case fileLastTax = "filed_previous_year_tax_return"             case heatRepairs = "heating_system_needs_repairs"             case receivingMax = "received_maximum_benefit"           //  case personDetails = "person_details"          //   case marital1 = "marital_status"          //   case age1 = "age"          //   case pregnant = "pregnant"         }     } struct Order: Encodable {     let household: Eligibility } let order = Order(household: Eligibility(residence: "PA", hhmembers: 1, receivingBen: [], unhoused: false, utilityType: ["Peco"], residenceType: "other", propertyTax: false, homeRepairs: false, fileLastTax: false, heatRepairs: false, receivingMax: ["cip": false])) let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let orderJsonData = try! encoder.encode(order) print(String(data: orderJsonData, encoding: .utf8)!) Console: {   "household" : {     "region" : "PA",     "residence_type" : "other",     "at_risk_of_homelessness" : false,     "property_tax_past_due" : false,     "utility_providers" : [       "Peco"     ],     "home_needs_repairs" : false,     "filed_previous_year_tax_return" : false,     "household_size" : 1,     "receiving_benefits" : [     ],     "heating_system_needs_repairs" : false,     "received_maximum_benefit" : {       "cip" : false     }   } }
3
0
1.2k
Mar ’22
Button w/ condition on .sheet is not working
I have a button which is connected to a presented .Sheet when pressed which has simple if/else statement inside. However, when this particular Bool ssdiElig is true it still registers as false on the view. Here is my button code and below that the function that gives me the ssdiElig value (bool) for the .sheet if/else statement.                 ZStack {                     VStack {                         Button(action: {mspEligibility(); ssdiEligibility(); ssiEligibility(); mspEligibility2(); PAzipcode(); mspEligibility3();                             self.isOpen = true                             print(ssdiElig)                         }, label: {                             Text("View Results")                         }).sheet(isPresented: $isOpen, content: {                             if ssdiElig {                             Text("ssdi yes")                             } else {                             Text("ssdi no")                             }                         }                     )} This function will give ssdiElig Bool the value    func ssdiEligibility() {         if disabled == true && income <= 803 {             print("SSDI Eligible")             ssdiElig = true         } else if ssdiBen == true || ssiBen == true {             print("Not SSDI Eligible")             ssdiElig = false       } else {             print("Not SSDI Eligible")             ssdiElig = false         }     } Inside the console, ssdiElig prints out true. Also, SSDI Eligible is printed out as well. So, to me, its just the if statement that isn't working for some reason?
1
0
625
Feb ’22
Yes / No RadioButtons in form (swiftUI)
I'm looking to create RadioButton like buttons inside a form that the user can select Yes / No - (true / false). As of right now, a screen shot and code is below: So far, I pretty much have the button code and nothing Binded to these two buttons yet.                     Section("test button                                                        Yes    No") {                         HStack {                             Spacer()                             Button(action:  {                             }, label: {                                 Image(systemName: "circle")                                     .renderingMode(.original)                                     .resizable()                                     .aspectRatio(contentMode: .fit)                                     .frame(width: 18, height: 18)                             })                                 .padding(10)                             Button(action: {                             }, label: {                                 Image(systemName: "circle")                                     .renderingMode(.original)                                     .resizable()                                     .aspectRatio(contentMode: .fit)                                     .frame(width: 18, height: 18)                             })                         }                     } A couple things I'd like to do: Connect these two buttons to a Bool() - Maybe it should be a group and not separate? Can only select one at a time. 2a. an OnTapGesture to change button to be a fill when selected. I do have a couple of custom button styles that are NOT connected to the code yet but thought I'd show these in case additional information is needed. Two different styles, a My ButtonStyle, and a MyButtonPressed style     struct MyButtonStyle: ButtonStyle {       func makeBody(configuration: Self.Configuration) -> some View {         configuration.label           .padding()           .foregroundColor(.white)           .background(configuration.isPressed ? Color.red : Color.blue)           .cornerRadius(8.0)       }     }     struct MyButtonPressed: ButtonStyle {       func makeBody(configuration: Self.Configuration) -> some View {         configuration.label           .padding()           .foregroundColor(.white)           .background(configuration.isPressed ? Color.red : Color.blue)           .cornerRadius(8.0)       }     } Thanks! If you need any additional info, please ask.
1
0
1.8k
Feb ’22
Make if/else statements work properly in Presented Sheet
I'm having a difficult time running a couple functions on a .sheet when a button is selected. Pretty much, when I select the View Results button and the sheet opens, both functions are running as if they are not of true value, however I do print the values of these Boolean variables as the button is hit and they they print out the correct values. I have two major toggles here. One called Disabled & the other MedicareBen along with their State's:     @State var disabled: Bool = false     @State private var medicareBen: Bool = false                                          Section("Does anyone have:")    {                         Toggle(isOn: self.$medicareBen) { Text("Medicare")}                         .tint(.blue)                         Toggle(isOn: self.$disabled) { Text("A Disablility")}                         .tint(.blue)                     } I have two functions that determine the Booleans final value: The first function below, mspEligibility() below primarily involves the MedicareBen toggle above, while the second function, ssdiEligibility() involves the disabled button above.     @State var elig: Bool = false          func mspEligibility() {             if hhmembers == 1 && age >= 17 && income <= 1449 && incomefreq == .Monthly && mspBen == false && medicareBen == true && marital == .Single || marital == .Divorce || marital == .Widow {             print("MSP Eligible 1")             elig = true         } else if hhmembers == 1 && age >= 17 && income <= 17388 && incomefreq == .Yearly && mspBen == false && medicareBen == true && marital == .Single || marital == .Divorce || marital == .Widow {             print("MSP Eligible 1")             elig = true         } else if medicareBen == false {             print("Not MSP Eligible")             elig = false         } else if ssiBen == true || medicaidBen == true || mspBen == true || marital == .Married {             print("Not MSP Eligible")             elig = false         } else if hhmembers >= 2 {             print("Not MSP Eligible")             elig = false         } else {             print("Not MSP Eligible")             elig = false         }     } The function that involves the Disabled toggle:   @State var ssdiElig: Bool = false         func ssdiEligibility() {         if disabled == true && income <= 803 {             print("SSDI Eligible")             ssdiElig = true             disabled = true         } else if ssdiBen == true || ssiBen == true {             print("Not SSDI Eligible")             ssdiElig = false             disabled = false         } else {             print("Not SSDI Eligible")             ssdiElig = false             disabled = false         }     } Below is the button, which carries a bunch of different Eligibility functions that aren't really involved here. However, the button also presents a .sheet has 2 conditional statements that are a bit flaky. As I mentioned you'll see I print a few different things in the console, print(elig) , print(ssdiElig) , print(disabled), the Boolean values end up coming up as expected based on the prior functions I pasted above but it seems I have to toggle the disability button or Medicare button a couple times before the if conditions work properly. Is there a way around this? Or, maybe somehow binding them to another View the sheet opens? any thoughts?                ZStack {                   VStack {                         Button(action: {mspEligibility(); ssdiEligibility(); ssiEligibility(); mspEligibility2(); PAzipcode(); mspEligibility3();                             self.isOpen = true                             print(elig)                             print(ssdiElig)                             print(disabled)                                                     }, label: {                                                         Text("View Results")                                                  }).sheet(isPresented: $isOpen, content: {                             if ssdiElig {                                 ZStack {                                    RoundedRectangle(cornerRadius: 25)                                        .fill(Color.white)                                         .frame(width: 375, height: 125)                                         .shadow(color: Color.black.opacity(0.5), radius: 10, x: 10, y: 10)                                         .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)                                     HStack {                                         Text("Eligible for SSDI")                                             .font(.headline)                                             .padding(60)                                         Image(systemName: "face.dashed")                                             .resizable()                                             .frame(width: 60, height: 60)                                             .padding(7)                                     }                                 }                             } else {                                 Text("No")                             }                                 if elig == true {                                                                       Text("Eligible for MSP")                                     ZStack {                                         RoundedRectangle(cornerRadius: 25)                                             .fill(Color.white)                                             .frame(width: 375, height: 125)                                             .shadow(color: Color.black.opacity(0.5), radius: 10, x: 10, y: 10)                                            .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)                                         HStack {                                            Text("Eligible for MSP")                                             .font(.headline)                                             .padding(60)                                             Image(systemName: "face.dashed")                                                 .resizable()                                                .frame(width: 60, height: 60)                                                .padding(7)                                         }                                     }                                 } else {                                     Text("No")                                 }                         }                     )}                 }
2
0
708
Feb ’22
If/else Statements running back-to-back
What's happening here is when I select the View Results button, a .sheet screen is presented which shows some results. I have two if statements, one after the other, where I believe this is where my problem lies. Both of these toggles, Medicare & Disability reflect these two if statements in the code below. If seems to me that since the if ssdiElig statement, is below the if elig statement, I'm unable to see the results from toggling JUST the Disability button. I've tried putting these two if statements in their own functions but that didn't work well and created many errors. My question is, is there a better way to put this code together so if I select the Disability button without interacting with the Medicare button, the Disability if statement will run on it's own                 ZStack {                     VStack {                         Button(action: {mspEligibility(); ssdiEligibility(); ssiEligibility(); mspEligibility2(); PAzipcode(); mspEligibility3()                             self.isOpen = true                             print(elig)                             print(ssdiElig)                         }, label: {                             Text("View Results")                         }).sheet(isPresented: $isOpen, content: {                                 if elig == true  {                                     ZStack {                                         RoundedRectangle(cornerRadius: 25)                                             .fill(Color.white)                                             .frame(width: 375, height: 125)                                             .shadow(color: Color.black.opacity(0.5), radius: 10, x: 10, y: 10)                                             .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)                                         HStack {                                             Text("Eligible for MSP")                                                 .font(.headline)                                                 .padding(60)                                             Image(systemName: "face.dashed")                                                 .resizable()                                                 .frame(width: 60, height: 60)                                                 .padding(7)                                         }                                     }                                 } else {                                     Text("")                                 }                             if ssdiElig == true {                                 ZStack {                                     RoundedRectangle(cornerRadius: 25)                                         .fill(Color.white)                                         .frame(width: 375, height: 125)                                         .shadow(color: Color.black.opacity(0.5), radius: 10, x: 10, y: 10)                                         .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)                                     HStack {                                         Text("Eligible for SSDI")                                             .font(.headline)                                             .padding(60)                                         Image(systemName: "face.dashed")                                             .resizable()                                             .frame(width: 60, height: 60)                                             .padding(7)                                     }                                 }                             } else {                                 Text("")                             }                         })
1
0
422
Feb ’22
Using a variable from a Function
Is there any simple examples of the ability to grab a variable from a function? For instance, if a certain thing happens in a function, then += 1 would be added to the variable. I'd like to grab that variable and use it in a Conditional statement in the View. Example below which I'm not sure how to work. I have a function like so below: func mspEL() -> Int { var msp = 0 if age > 18 { print("Elig") msp += 1 } else { print("No" } I have a View called ResultsView() which I'm trying to grab the msp variable from the function above and use it in a Conditional statement to show some Text. Eg; If the variable is greater than 0, write this Text.     struct ResultsView: View {         @State var result = msp         var body: some View {             if result > 0 {                 Text("You are Eligible!")             } else {                 print("")             }         }     }
4
0
1.8k
Feb ’22
Get function variable and use in View
I'm having some difficultly grabbing a variable from a function and using it in a View for Text() purposes. I have a simple function like so: func mspEL() -> Int { var msp = 0 if age > 18 { print("Elig") msp += 1 } else { print("No" } I have a View called ResultsView() which I'm trying to get the msp variable for an info statement like so:     struct ResultsView: View {         @State var result = msp         var body: some View {             if result > 0 {                 Text("You are Eligible!")             } else {                 print("")             }         }     } But I'm unable to get this to work. As I mentioned, looking to see if the msp variable is larger than 0 and if is, print Text in the View. What can I do to get this? Thanks!
0
0
345
Feb ’22
Error Message while Interacting w/ Multiple NavLinks
I'm receiving an error message in the console when navigating back to a View. I'll show you wants happening: So, let's say I have a NavigationView() in a ParentView, and what I wanted in the app was minimal BackButton appearance, so I added this to the bottom of the ParentView file: extension UINavigationController {   open override func viewWillLayoutSubviews() {     navigationBar.topItem?.backButtonDisplayMode = .minimal   } } ParentView -> ChildView1 -> ChildView2 On ChildView1, I interact with a Picker. If a certain option is selected from the picker, a NavLink appears to click towards ChildView2. Now when I return back to ChildView1 from ChildView2, I not only get this error message in the console but the BackButton on ChildView1 also disappears and the ability to go back to the ParentView is gone. Error: [6326:2400762] changing items while animating can result in a corrupted navigation bar I can't seem to find much documentation out there regarding this error when searching, any advice? Thanks!
1
0
1.1k
Feb ’22
Remove Image in ParentView once TextField in ChildView has a value
In my ParentView I have a NavigationLink that goes to a ChildView like so: HStack {  NavigationLink(destination: AddMemberView(newMemberFirst: $NMFirst, newMemberLast: $NMLast, newMemberAge: $NMAge), label: {}).navigationBarHidden(true) Text("\(NMFirst) \(NMLast)") Image(systemName: "person.crop.circle.fill.badge.plus") .renderingMode(.original) .foregroundColor(Color(.systemBlue)) .font(.system(size: 30)) } My goal here is that once the $newMemberFirst TextField in the ChildView,AddMemberView() has a value in it, the Image person.crop.circle.fill.badge.plus will disappear in the ParentView. Thanks!
1
0
436
Feb ’22
Insert Image into RoundedRectangle()
So, I have a RoundedRectangle() embedded inside a NavLink (see below) however I am trying to add a system Image to the RoundedRectangle() so the image appears in the center of the rectangle. If I place Image(systemName: "heart.fill") in any line between NavLink and .Fill, the heart shows up on the left / right of the rectangle or completely off screen. Any suggestions? Thanks.  NavigationLink(destination: EmptyView()) {             RoundedRectangle(cornerRadius: 25)                                 .fill(Color.newRed) }
1
0
3.3k
Feb ’22