-1

pardon me for beginner's question, I took this piece of code straight out of an online tutorial, didn't compile, I guess the course is outdated (my swift version is 2.2)

var years = edtYears.text.toInt();

It always complain something like Value of optional type String? not unwrapped, I tried to put ? in already, still no luck. Any tip, thanks

EyeQ Tech
  • 7,198
  • 18
  • 72
  • 126

3 Answers3

0

Try this:

let years = Int(edtYears.text ?? "0")
Daniel Tran
  • 6,083
  • 12
  • 25
0

To keep it doing the same thing, this will do:

var years = Int(edtYears.text!)
Jeshua Lacock
  • 5,730
  • 1
  • 28
  • 58
-1

Try something like this:

var years = String()


override func viewDidLoad() {
         super.viewDidLoad()
         years = yourTextField.text
         print(years)
}

so this is for string

and now for Int :

var years = Int()

override func viewDidLoad() {
     super.viewDidLoad()
     years = Int(yourTextField.text!)
     print("\years")
}
Otar
  • 84
  • 4
  • The original code converted the string to an Int. This will keep the text a String. – Jeshua Lacock Sep 03 '16 at 05:01
  • yes that's right ! to convert in In Int he will have to use this: var years = Int() override func viewDidLoad() { super.viewDidLoad() years = Int(yourTextField.text!) print("\(years)") } – Otar Sep 03 '16 at 05:05