In: Computer Science
Given, We need to declare the array variable in swift such that it can store instances of any class type.
Generally, Arrays are used to store the homogenous type of data. i.e; data of a particular class or type ca be stored. The same definition applies to arrays in swift also.
We can use the simple array declaration using the following syntax if and only if we know the type of instance to be stored and only that particular type is stored.
The syntax is as follows :
var arrayName = [instanceType]()
The syntax stores only that particular type of instance you need to store.
But, there is a small difference in swift that if we do not know the type of instance we need to store, we can use a particular way to store the data. This helps in storing instances of any class type.
There are 2 ways of doing it:
1. Using AnyObject.
2 Using Any.
The only difference that exist between the two is that AnyObject can represent instance of any class type whereas Any can represent an instance of any type including the function types.
We use them in the following way:
1. Using Any :
Source Code :
import Foundation
import Glibc
var arr = [Any]()
arr.append("hello")
arr.append(2)
arr.append(3.256)
print(arr[0])
print(arr[1])
print(arr[2])
Output :
hello 2 3.256
2. Using AnyObject :
Source Code :
import Foundation
import Glibc
class student {
var studname = "raja"
var mark = 98
var mark2 = 95
}
class teacher
{
var name = "john"
}
var arr = [AnyObject]()
let m = student()
let t = teacher()
arr.append(m)
arr.append(t)
print(arr[0])
print(arr[1])
Output :
main.student main.teacher
Here, We can see that the two values in the array are the objects of the classes student and teacher respectively.
Simple Synatx :
Source Code :
import Foundation
import Glibc
class student
{
var studname = "raja"
var mark = 98
var mark2 = 95
}
var arr = [student]()
let s1 = student()
let s2 = student()
arr.append(s1)
arr.append(s2)
print(arr[0].studname)
print(arr[1].studname)
Output :
raja raja
The screenshots are as follows :
Using Any :
Using AnyObject :
Simple Syntax :
I hope that this will give you all the information you needed regarding arrays in swift and how to store the instances of a class in an array.