1 | initial version |
To return an array of its own type through a method in Swift, you can use the built-in generic type system.
Here's an example:
class MyClass {
var id: Int
init(id: Int) {
self.id = id
}
func createArray(count: Int) -> [MyClass] {
var array = [MyClass]()
for i in 0..<count {
let obj = MyClass(id: i)
array.append(obj)
}
return array
}
}
let myObj = MyClass(id: 1)
let myArray = myObj.createArray(count: 3)
print(myArray) // output: [MyClass(id: 0), MyClass(id: 1), MyClass(id: 2)]
In this example, createArray
method creates an array of MyClass
instances based on the count parameter passed in. The method returns an array of the same type as MyClass
.
To achieve this result, we have created an empty array of type [MyClass]
at the beginning of the method. Inside the for loop, we create new instances of MyClass
and append them to the array
. Finally, we return the array
from the method.