계산기 앱 만들기(UIkit, code base) 트러블 슈팅

김재우·2025년 4월 3일

문제 상황

  • 발생 일시: 2025-04-03
  • 발생 환경: iOS 18.2, Xcode 16.2, UIKit 사용
  • 기능: NSExpression 을 이용해 계산을 진행
  • 문제 내용:
if buttonText == "=" {
   let result = calculate(expression: currentText)
   }

로 작성을 하면 오류가 발생


원인 분석

 func calculate(expression: String) -> Int? {
            let expression = NSExpression(format: expression)
        if let result = expression.expressionValue(with: nil, context: nil) as? Int {
            return result
        } else {
            return nil
        }
    }
  • label.text는 String? 타입

  • calculate(expression:) 함수는 Int?타입을 반환

  • Int? 값을 String?에 바로 할당할 수 없음

  • result를 String으로 타입 변환 해야함


해결 과정

Optional Binding (if let) 사용

if buttonText == "=" {
            if let result = calculate(expression: currentText) {
                label.text = String(result) // Int → String 변환
            } else {
                label.text = "Error" // 계산 실패 시 기본값
            }
            return
        }

로 다시 작성


결과

  • 시뮬레이터로 계산기의 기능이 제대로 작동함
profile
iOS 스타터 6기

0개의 댓글