-1

I have written some code in Xcode and the error is on the last line. Can someone help me convert the string to an integer?

@IBAction func btnCalc(_ sender: Any) {
    let numb1 = Int(txtN1.text!)
    let numb2 = Int(txtN2.text!)

    let calcResult = (numb1)! + (numb2)!
    labelResult.text = (calcResult)
}
An. Jorge
  • 61
  • 1
  • 9
  • Possible duplicate of [Convert Int to String in Swift](http://stackoverflow.com/questions/24161336/convert-int-to-string-in-swift) – Hamish Mar 02 '17 at 21:52
  • you can use String interpolation, String initializer or get its description property value. `"\(calcResult)"` , `String(calcResult)` or `calcResult.description` – Leo Dabus Mar 02 '17 at 22:13
  • @LeoDabus Note the latter is discouraged by the Swift team. – Hamish Mar 02 '17 at 22:14
  • @Hamish Thanks for the feedback !!! Do you have a link (reference) of it? – Leo Dabus Mar 02 '17 at 22:22
  • give us the link please – An. Jorge Mar 02 '17 at 22:24
  • I could't find any note at the docs https://developer.apple.com/reference/swift/int/1539460-description – Leo Dabus Mar 02 '17 at 22:27
  • @LeoDabus Oops sorry, I meant to add a link, but got sidetracked – the note is in the [`CustomStringConvertible`](https://developer.apple.com/reference/swift/customstringconvertible) docs: "*Accessing a type’s `description` property directly or using `CustomStringConvertible` as a generic constraint is discouraged.*" – Hamish Mar 02 '17 at 22:29
  • 1
    Possible duplicate of [Convert Int to String in Swift](http://stackoverflow.com/questions/24161336/convert-int-to-string-in-swift) – JAL Mar 02 '17 at 22:30

1 Answers1

2

Int(myString)

Swift 1.x

let myString: String = "256" let myInt: Int? = myString.toInt()

Swift 2.x, 3.x

let myString: String = "256" let myInt: Int? = Int(myString)
nacho4d
  • 43,720
  • 45
  • 157
  • 240
creeperspeak
  • 5,403
  • 1
  • 17
  • 38