簡體   English   中英

Swift AnyObject 參數

[英]Swift AnyObject Parameters

我在我的 Swift 應用程序中使用以下初始化程序:

init(items :NSArray, identifier :String, configureCellClosure: (cell :AnyObject, item :AnyObject) -> ()) {

}

現在,我需要利用,所以我執行以下操作:

 let sessionsDataSource = SessionsDataSource(items: [], identifier: "") { (cell :UITableViewCell, item :Session) -> () in


        } 

但它抱怨我指定了 UITableViewCell 和 Session 對象。 當我使用 AnyObject 時,我不能提供我想要的任何東西嗎?

不,Swift 太在意類型安全了。 您聲稱要傳入一個 [閉包作為參數] UITableViewCell 和一個會話,而實際上您並沒有做出這樣的保證。 函數由它們的整個簽名定義,其中包括函數名稱以及參數的類型和數量。 您正在做出一些更大的設計錯誤或不正確的假設,以至於您覺得您需要在構造函數中接受一個不適合您需要使用它的閉包。

為什么不強制調用構造函數的代碼傳入正確的東西呢?

閉包總是可以基於任何神秘的邏輯,將cellUITableViewCell向下轉換到其中的MyFunkyTableViewCell以配置特定於后一個子類的屬性,並根據其他條件邏輯執行其他向下轉換。

類型簽名不匹配。 init聲明中,閉包的類型是(AnyObject, AnyObject) -> () ,但是當你真正調用它的時候,閉包的類型是(UITableViewCell, Session) -> () 這些不是相同的類型。

init聲明中,您告訴編譯器您可以使用任何對象類型的兩個參數調用閉包。 編譯器相信你。 當您最終調用它時,它不會查看您實際傳遞給閉包的內容。

但是后來,當你真正傳入一個閉包時,你傳遞的是一個不能接受任何兩個對象引用的閉包。 它需要對UITableViewCell的引用和對Session的引用。 如果程序調用的東西,這不是一個封閉UITableViewCellcell ,或東西是不是一個Sessionitem ,程序可能會崩潰。 但是你告訴編譯器(在init聲明中)你可能確實用UITableViewCellSession以外的東西來調用閉包。 編譯器拒絕編譯這個程序,因為它可能會崩潰。

試試這個:

let callback = { (cell: AnyObject, item: AnyObject) -> () in
    guard let cell = cell as? UITableViewCell else {
        return
    }
    guard let item = item as? NSPredicate else {
        return
    }

    // do work here
}

更新

你的新錯誤是因為你試圖調用configureCellClosure ,它是一種類型,而不是closure ,它是該類型的參數(到init )。 您需要將configureCellClosure重命名為ConfigureCellClosure ,在SessionDataSource中創建一個ConfigureCellClosure類型的屬性,在init初始化該屬性,並在tableView:cellForRowAtIndexPath:調用該屬性。

    typealias ConfigureCellClosure = (cell: UITableViewCell) -> ()

    private let closure: ConfigureCellClosure

    init(closure: ConfigureCellClosure) {
        self.closure = closure
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        closure(cell: cell)
        return cell
    }

暫無
暫無

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

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