可以在Swift函数中返回不同的数据类型吗?

Mat*_*des 2 generics ios swift

我正在使用UITableViewin Swift,我有一个函数,它根据某些条件返回行数,另一个函数返回每个节的标题.两个函数具有相同的主体,相同的条件,但第一个函数返回Intdat类型,第二个函数返回String数据类型.

我可以以某种方式使这个泛型函数成为一个返回一些通用值的函数,但该值必须是'Int'用于第一个函数和String第二个函数.

下面的代码是返回行数的函数.相同的主体去返回部分标题的功能.它的返回类型是String.

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
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答.

pac*_*ion 5

你应该返回这样的tuple类型:

func getNumberOfRows(for section: Int) -> (Int, String) {}
Run Code Online (Sandbox Code Playgroud)

此外,对于您的代码,您可以使用typealias关键字为您的名称定义名称tuple:

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

func getNumberOfRows(for section: Int) -> NumberOfRowsInfo {}
Run Code Online (Sandbox Code Playgroud)

并获得这样的数据:

let info = getNumberOfRows(for: section)
print("Row: \(info.row), string: \(info.someString)")
Run Code Online (Sandbox Code Playgroud)