2016-06-20 2 views
1

스위프트 초보자는 여기에 있습니다. 나는 Swift의 교과서를 읽고 이상한 표현을 발견했다 ...이 코드는 무엇인가 (두 번째 "let"라인)하고 있는가? 등호와 UITableVIewCell 메소드 사이를 살펴보십시오. 내게는 "c는 무효가 아니며 선택적이어야하며 C가 언랩되어야합니다 ...."처럼 보입니다.스위프트의 브래킷에 할당

(c! = nil)? 기음!

검색 엔진에서 좋은 검색 키워드를 만들 수 없어 인터넷 (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에 응답합니다.

1

그것은 ternary operator입니다. 일반적으로 시작하기에 당신의 머리를 감싸기가 어렵습니다. 다음과 같이 작동합니다.

(c! = nil)이 true이면 (즉 c가있는 경우) cell == 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)