これらは似ていますが、同じではありません。
as
は、オブジェクトを別のオブジェクトとして使用することをコンパイラに知らせるものです。
例では、tableView.dequeueReusableCell
は、のいずれかを含むことができるオプションのUITableViewCell?
を返します。
Optionalsはどちらかif/let
で、いくつかの方法でアンラップすることができます。
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") {
// cell is a UITableViewCell here, not an optional
}
// cell doesn't exist here anymore
がguard
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else {
// cell is nil so it's not even created. We HAVE to exit here
return
}
// cell is a cell is UITableView here, no optional
を使用したり、安全ではないとされ、それを強制的にクラッシュするアプリケーションを引き起こす可能性があります。バックあなたの質問に今
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
// cell will be UITableViewCell!, which is an optional that will
// crash if you try to use it and it's nil
を(個人的に私は同じくらい私はできる限りこれらを回避し、そして唯一のIBOutlets
でそれらを使用)、あなたは定期的なオプションであるUITableViewCell?
を、持っています。
最初の例では、最初に!
で強制アンラップしてから、UITableViewCell
にキャストします。これは実際にはforce-unwrapped-optionalのUITableViewCell
になります。これは、アプリがゼロで、使用しようとするとクラッシュすることになります。
2番目の例では、UITableViewCell?
をUITableViewCell!
とすると、同じシナリオになります。
どちらの例でも、cell
を使用している場合、?
または!
を使用する必要があります。これは既に強制解除されているためです。
ただし、force-unwrapped-optionalsを使用しないようにガードを使用することをお勧めします。これは私がカスタムセルを処理する方法である:私はtableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
を使用しています、このメソッドは、オプションを返さないので、あなたは、カスタムクラスを持っていないセルを使用したい場合は
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? CustomCell else {
fatalError("CustomCell is not in the table view")
// Crash with a custom message instead of a generic one
}
注意、あなたはこれを使用することができ、アンラッピングについて心配する必要はありません。