泛型函数声明引发错误

时间:2018-08-28 16:12:26

标签: ios swift generics

我需要声明一个泛型函数,该函数返回一个泛型单元格,为此,我实现了以下操作,

private func getVisibleCellAs<Cell>() -> Cell? {
    if let visibleCell = self.registrationTableView.visibleCells.first, let expectedCell = visibleCell as? Cell {
        return expectedCell
    }
    return nil
}

现在,我称其为

if let personalDetailsCell = self.getVisibleCellAs<PersonalDetailsTableViewCell>() {
            return personalDetailsCell.validatePersonalDetails()
}

但是,它显示为(在函数调用中)错误

Cannot explicitly specialize a generic function

如果尝试致电。

2 个答案:

答案 0 :(得分:1)

Swift不允许您手动指定要传递给函数的通用参数,而是必须可以从上下文计算得出。您在这里至少有三个选择:

  1. 声明变量类型:

    if let personalDetailsCell: PersonalDetailsTableViewCell = self.getVisibleCellAs() { ... }
    
  2. 广播结果:

    if let personalDetailsCell = self.getVisibleCellAs() as PersonalDetailsTableViewCell { ... }
    
  3. 如果将结果传递给另一个函数,则编译器应该能够推断出:

    func configure(personCell cell: PersonalDetailsTableViewCell) { ... }
    // later on
    configure(personCell: self.getVisibleCellAs())
    

答案 1 :(得分:0)

您不能明确地专门化这样的泛型函数。

但是您可以这样做:

Dim i As Long
Dim LastRow As Long

LastRow = Cells(Rows.Count, rowtofilter).End(xlUp).Row

'Search for merged cells and not "string1" in column2 and not "string2" in column4, replace text
For i = rowtofilter To LastRow
    If Range(ColumnLetter1 & i).MergeArea.Cells.Count > 1 And Range(ColumnLetter2 & i) <> "string1" And Range(ColumnLetter4 & i) <> "string2" Then
        Range(ColumnLetter3 & i).Value = "Merged Cells"
    End If
Next i

'Search for merged cells and not "string1" in column2 and not "string2" in column4, delete rows
i = LastRow - rowtofilter
Do While i > (rowtofilter - 1)
    If Range(ColumnLetter1 & i).Value = 0 And Range(ColumnLetter2 & i) <> "string1" And Range(ColumnLetter4 & i) <> "string2" Then
        Range(ColumnLetter1 & i).EntireRow.Delete
    End If
    i = i - 1
Loop