Struct Definition:

struct structName 
{
    //properties 
}

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.

struct_init

struct_ex1

We get error if we pass only some properties

struct_error.png

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

struct_cutsom_init

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

struct_multi_init.png

Struct is Value type :

Struct is value type unlike class which is reference type.

For ex.

//1
struct Person {
    var firstName : String
    var lastName: String
}

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

//3
var secondPerson = firstPerson

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

//5
firstPerson.firstName = "Harshal"

//6
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.

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

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 –  paypal.me/SandeshSardar

download

Advertisements