1

Novice in Swift and I'm having a frustrating problem. The program compiles correctly and runs without crashing. The program is supposed to calculate the age of a cat in cat years based user-inputted human years. After pressing the button, however, the result is diplayed with the word "Operator" appended by the cat years which is delimited by parenthesis, i.e., Optional(35). Here is my code:

@IBOutlet weak var getHumanYears: UITextField!
@IBOutlet weak var displayCatYears: UILabel!
@IBAction func calculateCatYears(_ sender: Any) 
{
    if let humanYears = getHumanYears.text
    {
        var catYears: Int? = Int(humanYears)
        catYears = catYears! * 7
        let catYearsString: String = String(describing: catYears)

        displayCatYears.text = "Your cat is " + catYearsString + " years old"
    }
}

Does anyone know what I'm doing wrong? Thank you for your valuable input!

Marcus Kim
  • 283
  • 2
  • 12

3 Answers3

5

The problem is here:

String(describing: catYears)

catYears is an Optional<Int>, a string that describes an Optional<Int> will be in the format of Optional(<value>) or nil. That's why you get Optional(35).

You need to unwrap catYears!

String(describing: catYears!)

Or, remove String(describing:) all together and do:

if let humanYearsText = getHumanYears.text, let humanYears = Int(humanYearsText)
{
    let catYears = humanYears * 7
    displayCatYears.text = "Your cat is \(catYears) years old"
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

As other mentioned, it is because var catYears: Int? = Int(humanYears), thus catYears is an optional. And the String(describing: ...) for an optional does print Optional(rawValue).

What you want is to make sure you have the value, and not an optional when you print it. If you're 100% certain that you do have a Int value in the string, you can do it with !.

However, I suggest that you don't use the ! operator because that will crash your application if there are characters in the textfield.

if let text = getHumanYears.text, let humanYears = Int(text)
{
    let catYears = humanYears * 7
    displayCatYears.text = "Your cat is \(catYears) years old"
} else {
    displayCatYears.text = "I don't know!" 
}
netdigger
  • 3,659
  • 3
  • 26
  • 49
0

Unwrap catYearsString. Use this let catYearsString: String = String(describing: catYear!) displayCatYears.text = "Your cat is " + catYearsString + " years old"

Output:

Test Code

var catYears: Int? = Int(7)
catYears = catYears! * 7
let catYearsString: String = String(describing: catYears!)

print("Your cat is " + catYearsString + " years old")

enter image description here

dahiya_boy
  • 9,298
  • 1
  • 30
  • 51