Thegasman2000
Thegasman2000

Reputation: 115

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!)
    print(newuser.firstName)
    print(newuser.lastName)

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
    print(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?

Upvotes: 1

Views: 4740

Answers (2)

Hardik Thakkar
Hardik Thakkar

Reputation: 15951

You can also user structure variable directly to save value and use in another ViewController like below

struct NewUserStruct {
    static var newUserDetails: NewUserStruct = NewUserStruct()

    var firstName: String = ""
    var lastName: String = ""
}

You can assign value like this

NewUserStruct.newUserDetails.firstName = "ABC"
NewUserStruct.newUserDetails.lastName = "XYZ"

and you can get this value in another view like this

print(NewUserStruct.newUserDetails.firstName)

You can reset it's value when your requirement is done

NewUserStruct.newUserDetails = NewUserStruct()

Upvotes: 0

Sahil
Sahil

Reputation: 9226

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

Upvotes: 1

Related Questions