條件綁定:如果讓錯誤 - 條件綁定的初始化程序必須具有可選類型我試圖從我的數(shù)據(jù)源和以下代碼行中刪除一行:if let tv = tableView {導致以下錯誤:條件綁定的初始化程序必須具有Optional類型,而不是UITableView這是完整的代碼:// Override to support editing the table view.func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
if let tv = tableView {
myData.removeAtIndex(indexPath.row)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)我該如何糾正以下問題? if let tv = tableView {
3 回答

繁星淼淼
TA貢獻1775條經(jīng)驗 獲得超11個贊
if let
/ if var
optional綁定僅在表達式右側的結果是可選的時才有效。如果右側的結果不是可選的,則無法使用此可選綁定。這個可選綁定的要點是檢查nil
并僅使用變量(如果它是非變量)nil
。
在您的情況下,該tableView
參數(shù)被聲明為非可選類型UITableView
。它保證永遠不會nil
。所以這里的可選綁定是不必要的
func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source myData.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
我們所要做的就是擺脫if let
和改變任何出現(xiàn)tv
在它剛tableView
。

UYOU
TA貢獻1878條經(jīng)驗 獲得超4個贊
對于我的具體問題,我不得不更換
if let count = 1 { // do something ... }
同
let count = 1if(count > 0) { // do something ... }

拉莫斯之舞
TA貢獻1820條經(jīng)驗 獲得超10個贊
在您使用自定義單元格類型的情況下,例如ArticleCell,您可能會收到錯誤消息:
Initializer for conditional binding must have Optional type, not 'ArticleCell'
如果您的代碼行看起來像這樣,您將收到此錯誤:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as! ArticleCell
您可以通過執(zhí)行以下操作來修復此錯誤:
if let cell = tableView.dequeReusableCell(withIdentifier: "ArticleCell",for indexPath: indexPath) as ArticleCell?
如果你檢查上面的內容,你會發(fā)現(xiàn)后者正在為ArticleCell類型的單元格使用可選的強制轉換。
- 3 回答
- 0 關注
- 643 瀏覽
添加回答
舉報
0/150
提交
取消