簡體   English   中英

可以在Swift函數中返回不同的數據類型嗎?

[英]Can function in Swift return different data types?

我正在使用Swift UITableView ,我有一個函數,它根據某些條件返回行數,另一個函數返回每個部分的標題。 兩個函數具有相同的主體,相同的條件,但第一個函數返回Int dat類型,第二個函數返回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
}

謝謝你的回答。

你應該返回這樣的tuple類型:

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

此外,對於您的代碼的慣例,您可以使用typealias關鍵字來定義tuple名稱:

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

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

並獲得這樣的數據:

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

您可以使用具有兩種不同返回類型的相同函數,如下所示

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

然后它被調用為

let (yourIntegerValue,yourStringValue) = getNumberOfRows(for section:yourSectionNumber)

現在使用這兩個值來執行任務。

你可以返回tuple

func getNumberOfRows(for section: Int) -> (row:Int,title:String)

return如此return(row:suggestions.count,title:"Suggestions")

你可以使用

let tupple =  getNumberOfRows(for :0) 
tupple.row or  tupple.title

我會建議你做元組

你可以用這樣的元組來做:

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

getNumberOfRows(for: 3).0
getNumberOfRows(for: 3).1

您可以嘗試以下方式:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM