Thegasman2000 Thegasman2000 - 1 year ago 75
Swift Question

Append a value in Struct in Swift 3

So I have a struct in my BaseViewController

struct NewUserStruct {
var firstName: String = "Default First Name"
var lastName: String = "Default Last Name"

I then use this in the sending VC

let firstNameReg = inputFirstName.text
let lastNameReg = inputLastName.text

let newuser = NewUserStruct(firstName: firstNameReg!, lastName: lastNameReg!)

This works fine and prints the first and last name. I dont think I am saving this to the struct though! as when i call the struct in the final VC:

let newuser = NewUserStruct()
let firstNameLog = newuser.firstName

It prints the Default First Name string I set in the BaseViewController. How do I append the struct with the values in the sending VC?

Answer Source

You need to understand the concept of passing values(instances) from one controller to another. if you want to use the newuser instance values in other controller you must have to pass it from one controller to another using prepareForSegue but you are creating new instance NewUserStruct() in another controller or you can make shared properties using static or use them everywhere.

struct NewUserStruct {
 static var firstName: String = "Default First Name" 
 static var lastName: String = "Default Last Name"

NewUserStruct.firstName = "new name" 

in another controller

 print(NewUserStruct.firstName) // new name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download