1

guard迅速なステートメントの理解に応じて、次のことを行っています。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let identifier = "identifier"
    let dequeCell = tableView.dequeueReusableCellWithIdentifier(identifier)

    guard let cell = dequeCell else
    {
        // The following line gives error saying: Variable declared in 'guard'condition is not usable in its body
        cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
    }

    cell.textLabel?.text = "\(indexPath.row)"

    return cell
}

理解したいのは、guardステートメントで変数を作成し、関数の残りの部分でアクセスできるかということです。または、ガードステートメントはすぐに例外を返すかスローすることを意図していますか?

guardまたは、ステートメントの使用法を完全に誤解していますか?

4

1 に答える 1

4

ドキュメントはそれをかなりよく説明しています

ステートメントの条件が満たされた場合guard、コードの実行はguardステートメントの右中かっこの後に続行されます。オプションのバインディングを条件の一部として使用して値が割り当てられた変数または定数は、guard ステートメントが表示される残りのコード ブロックで使用できます。

その条件が満たされない場合、else ブランチ内のコードが実行されます。その分岐は、guardステートメントが表示されるコード ブロックを終了するために制御を転送する必要があります。これは、return、break、continue、throw などの制御転送ステートメントを使用して実行できます。または、 fatalError() など、返されない関数またはメソッドを呼び出すこともできます

dequeueReusableCellWithIdentifier:forIndexPath:特定のケースでは、推奨されるメソッドは常に非オプションの型を返すため、guard ステートメントはまったく必要ありません。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let identifier = "identifier"
    let dequeCell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
    cell.textLabel?.text = "\(indexPath.row)"
    return cell
}
于 2016-03-30T06:39:13.280 に答える