Struct in Swift

Struct Definition:

struct structName 

Example of Struct : 

struct Person {
    var firstName: String?
    var lastName: String?  

In Swift struct creates init method behind the scene. Unlike Class we did not need to write init method. While creating instance we need to either pass all the properties to that default init method or we can pass nothing *if properties are optional (just like in example).

For ex.



We get error if we pass only some properties


If we want to pass only some properties in init method, we need to create our own init method.


Also we can create multiple init method in struct with different number of parameters


Struct is Value type :

Struct is value type unlike class which is reference type.

For ex.

struct Person {
    var firstName : String
    var lastName: String

var firstPerson = Person(firstName: "Sandesh", lastName: "Sardar")

var secondPerson = firstPerson

print(firstPerson.firstName)    --- Sandesh
print(secondPerson.firstName)   --- Sandesh

firstPerson.firstName = "Harshal"

print(firstPerson.firstName)    --- Harshal
print(secondPerson.firstName)   --- Sandesh

1. created struct       2. created instance of struct Person     3. Assign instance variable firstPerson to variable secondVariable     4. Print Output. Both have same firstName           5. Change firstName of firstPerson to Harshal   6. Print output. firstPerson has new Name but secondPerson have Old name Sandesh. Because  struct is value type means while assigning value to new variable it creates the fresh object (create copy of object). In memory location in create separate location for both firstPerson and secondPerson.


Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –


2 thoughts on “Struct in Swift

  1. I’m now not sure where you are getting your info, however great topic. I must spend some time learning much more or working out more. Thank you for great info I used to be in search of this info for my mission.


Leave a Reply to Alex Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s