Tag: array

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.