2016-06-20 7 views
1

スウィフト初心者はこちらです。 私はSwiftの教科書を読んでいて、奇妙な表現を見つけました...このコードは何ですか(2番目の "let"行)ですか?等号とUITableVIewCellメソッドの間のことを見てください。 私には、 "cは無制限ではなく、オプションでなければならず、cはアンラップされるべきです...."と思われます。スウィフトのブラケット割当

(c!= nil)? c!

質問の検索エンジンで適切な検索キーワードを作成できないため、インターネット(Google)で検索することは難しいです。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    //create cells in table 
    let c = tableView.dequeueReusableCellWithIdentifier("table_cell") 
    let cell = (c != nil) ? c!: UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell") 
return cell 
} 

答えて

2

ライン

let cell = (c != nil) ? c!: UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell") 

を実証していますか? ternary operator

c != nilの場合はc!が返されます。それ以外の場合はUITableViewCellになります。

let cell = c ?? UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell") 

同様の質問/答えhere

コードは、演算子を合体nilを速記を使用するように簡単にすることができます。

1

ternary operatorです。あなたの頭を包み込んで始めるのは通常は少し難しいです。

(c!= nil)がtrue(つまりcが存在する)の場合は、cell == c!(:)の左側からです。一方、c の場合、(c!= nil)はfalseを返し、コロンの右側からcell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "table_cell")を返します。あなたはそれがどのように動作するかの理解を得るために、運動場でこれを周りにプレイしたい場合があります

let text = "foo" // try changing this to something else entirely 
let output = text == "foo" ? text : "bar" 
print(output)