HOW TO USE ARRAY OF STRUCT IN SWIFT

Swift provides a  number of features that makes struct better than classes in most of the cases. I had attended a workshop where it was majorly focussed on array of struct.

Let us wrap up on few of the benefits of array of structs:

  • Structs are relatively small and light.
  • Structs are copiable as copying is a better and safer rather than having multiple references to the same reference as in case of classes.
  • Less of memory leaks

DECLARE ARRAY OF STRUCT

class ViewController: UIViewController {

var arrayOfStruct:Array<datastruct> = Array<datastruct>()

}

Once we have declared an array of struct type, we need to define the struct i.e. datastruct in this case.

struct datastruct{

var id:String?

var title:String?

var description:String?

init(add: NSDictionary){

id = add[“id”] as? String

title = add[“title”] as? String

description = add[“description”] as? String

}

}

Here, we have initialised the struct with parameter of NSDictionary type. But we can take other parameters too of different data types unlike NSDictionary. For example,

init(id: String, title: String, description: String) {

id = id

title = title

description = description

}

This is a simple implementation of array of struct.

Advertisements

One thought on “HOW TO USE ARRAY OF STRUCT IN SWIFT

  1. You can certainly see your skills in the paintings you write. The world hopes for more passionate writers such as you who are not afraid to say how they believe. At all times go after your heart.

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s