Pavel Gatilov Pavel Gatilov - 5 months ago 17
iOS Question

Swift method which returns array

So, I have a question about how my class and struct interfaces should look like in Swift.
For example I have a class or struct which has method:

func getAllObjectsFromSomewhere() -> [Int]

but, imagine that this method not always return you some array of Int, so there are few different ways how to handle it.

  • func getAllObjectsFromSomewhere() -> [Int]?

  • func getAllObjectsFromSomewhere() throws -> [Int]
    Throws custom ErrorType with types like: NotFound or EmptyArray

  • func getAllObjectsFromSomewhere() -> [Int] { /* some code and then just return an empty Int array */ return [Int]() }

So, my question is, when and why I should take which approach of organising the interface? Does it make much difference? Is there any guidelines?


All three approaches are valid, depending on a situation:

  • When getting objects may or may not be possible, and impossibility does not necessarily mean an error, use [Int]?. This lets you differentiate between an empty array and no array at all.
  • When getting objects must always be possible, and impossibility to get them means you have an error, use throws
  • When inability to get objects should always be treated as an absence of objects, use [Int] and an empty array.