条件付きバインディング: if let error – 条件付きバインディングの初期化子は Optional 型である必要があります 質問する

条件付きバインディング: if let error – 条件付きバインディングの初期化子は Optional 型である必要があります 質問する

データ ソースから行を削除しようとしています。次のコード行です。

if let tv = tableView {

次のエラーが発生します。

条件付きバインディングの初期化子は UITableView ではなく Optional 型である必要があります

完全なコードは次のとおりです。

// 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 {

ベストアンサー1

if let/if varオプション バインディングは、式の右側の結果がオプションである場合にのみ機能します。右側の結果がオプションでない場合は、このオプション バインディングは使用できません。このオプション バインディングのポイントは、変数が であるかどうかをチェックしnil、 でない場合にのみ変数を使用することですnil

あなたの場合、tableViewパラメータは非オプション型として宣言されています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の出現をすべて に変更することだけです。tvtableView

おすすめ記事