Value of type 'String? ' has no Member 'Int'

Asked

Viewed 108 times

1

I have the following problem:

Value of type 'String? ' has on Member 'Int'

What is the reason for the error and what is the solution?

class ViewController: UIViewController {

    @IBOutlet var nameField: UITextField!
    @IBOutlet var happinessField: UITextField!

    @IBAction func add() {
        if nameField == nil || happinessField == nil {
            return
        }

        let name = nameField!.text
        let happiness = happinessField!.text.Int() // Erro aqui
        if happiness == nil {
            return }
        let meal = Meal(name: name!, happiness: happiness!)
        print("eaten: \(meal.name) \(meal.happiness)")

    }

}

3 answers

3


The error is because the structure String has no function called Int(). See in the official documentation.

If you are using Swift 1.x

Must use the toInt() and not Int().

let happines = happinessField!.text.toInt()

Or, from the Swift 2.x

let happines = Int(happinessField!.text)
  • That was in Swift 1.0 I think

0

There is no such function that you are trying to access.

If Voce wants to convert a String to Int, Voce needs to use:

let happiness:Int? = Int(happinessField.text)

0

For your solution I suggest using Guard Let. So already previously making validations of empty fields and that were not possible to cast for type.

guard let name =  nameField!.text else { return }    
guard let hapiness =  Int(happinessField!.text) else { return }

This makes the name and hapiness variables not optional and in the case of hapiness it was cast to Int correctly.

Refactoring the code would look that way:

class ViewController: UIViewController {

    @IBOutlet var nameField: UITextField!
    @IBOutlet var happinessField: UITextField!

    @IBAction func add() {
        guard let name =  nameField!.text, 
              let hapiness =  Int(happinessField!.text)
              else { return } 

        let meal = Meal(name: name, happiness: happiness)
        print("eaten: \(meal.name) \(meal.happiness)")

    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.