MattCodes MattCodes - 28 days ago 13
iOS Question

Can function in Swift return different data types?

I'm working with

and I have a function that returns number of rows based on some conditions and another function that returns title for every section. Both functions have the same body, the same conditions, but first function returns
dat type and second returns
data type.

Can I somehow make this one generic function, to be one that returns some generic value but that value must be 'Int' for first function and
for second function.

The code below is the function that returns number of rows. Same body goes for function that returns title for section. And its return type is

func getNumberOfRows(for section: Int) -> Int {

let parameters = SuggestionsTableSectionType.Parameters(recents: recents, suggestions: suggestions, section: section)

if SuggestionsTableSectionType.recentsAndSectionIsZero(parameters).isActive {
return recents.count
} else if SuggestionsTableSectionType.suggestionsAndSectionIsZero(parameters).isActive {
return suggestions.count
} else if SuggestionsTableSectionType.recentsAndSuggestionsAndSectionIsZero(parameters).isActive {
return recents.count
} else if SuggestionsTableSectionType.recentsAndSuggestionsAndSectionIsOne(parameters).isActive {
return suggestions.count
return 0

Thanks for your answers.

Answer Source

You should return the tuple type like this:

func getNumberOfRows(for section: Int) -> (Int, String) {}

Also, for convention your code, you can use typealias keyword to define name for your tuple:

typealias NumberOfRowsInfo = (row: Int, someString: String)

func getNumberOfRows(for section: Int) -> NumberOfRowsInfo {}

And get data like this:

let info = getNumberOfRows(for: section)
print("Row: \(info.row), string: \(info.someString)")