Ask Your Question
1

How can Swift return an array of its own type through a method?

asked 2023-07-06 00:23:03 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-06 00:51:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-06 00:23:03 +0000

Seen: 11 times

Last updated: Jul 06 '23