2016-06-19 3 views
0

Double (display.text!)을 래핑하지 않을 때 코드가 충돌합니다! 조건 경우 나는를 넣어하지만 제대로 작동 여기까지가예기치 않게 unwrapping 동안 nil 찾았습니다.

@IBAction private func buttonpress(sender: UIButton) 
{ 
    let digit = sender.currentTitle! 
    if userisinthemiddle 
    { 
     let currenttext = display.text! 
     display.text = currenttext + digit 
    } 
    else 
    { 
     display.text = digit 
    } 
    userisinthemiddle = true 
} 

를 작동하지 않았다하지만 난 속성으로 그것을 만들려고 할 때 그것은 일반적 아니다

var DisplayValue : Double 
{ 
    get 
    { 
     return Double(display.text!)! // thread 1 
     } 

    set 
    { 
     display.text = String(newValue) 
    } 
} 
+0

'display.text'가''abcdef ''이면 어떻게 될까요? – luk2302

+0

'text'는'nil'이거나'Double'으로 문자열을 표현할 수 없습니다. 그것을 확인하십시오. – vadian

+0

충돌을 피하기 위해'!'를 강제적으로 푸는 대신에 * n ?? coalescing 연산자 *'??'를 사용하는 것이 좋습니다 :'Double (display.text ?? "") ?? 0 '이다. – vacawama

답변

1

작동하지 않습니다 실제로 프로그램이 실패 할 경우 프로그램을 중단시키지 않는 한 변수의 랩핑을 강제 실행하는 것이 좋습니다 (내 경험으로는 거의 없습니다). 이 경우 문제를 진단하는 능력을 방해하는 것처럼 들립니다. (1) force unwrapping을 피하고 (2) 예기치 않은 값에 반응 할 수있는 더 나은 위치에있게하십시오.

@IBAction private func buttonPress(sender: UIButton) 
{ 
    guard let digit = sender.currentTitle else 
    { 
     assertionFailure("digit is nil.") 

     return 
    } 

    print("digit: \(digit)" 

    if userIsInTheMiddle 
    { 
     let currentText = display.text ?? "" // If display.text is nil, set currentText to an empty string 
     print("currentText: \(currentText)" 

     display.text = currentText + digit 
    } 
    else 
    { 
     display.text = digit 
    } 

    print("display.text: \(display.text)" 

    userIsInTheMiddle = true 
} 

var displayValue: Double 
{ 
    get 
    { 
     let text = display.text ?? "" 

     guard let double = Double(text) else 
     { 
      // You probably want to replace this `assertionFailure` and return a default value like 0 

      assertionFailure("text could not be converted to a Double") 

      return 
     } 

     return double 
    } 

    set 
    { 
     display.text = String(newValue) 
    } 
} 

몇 가지 질문 :

  1. 어떻게 재산 displayValue@IBAction 관련이 있습니까?
  2. + 연산자를 사용하여 여기에 두 개의 문자열을 연결하는 경우 display.text = currentText + digit입니다. 두 개의 숫자를 추가하려고하지 않는다는 것을 확인하십시오.
+0

대답과 설명 덕분에 많은 고맙습니다. 1. displayValue 속성을 한 번 만들어서 문자열을 double로 변환하고 double로 문자열을 다시 입력해야합니다. 2. currenttext에 "2"와 digit가 포함되어있는 경우 연결하려고합니다. "3"을 포함하고 "23"을 인쇄하고 싶습니다. –

관련 문제