-1

Hi I'm trying to convert string to Int in the below code: How Can I change the below code that converts string to Int so that the app doesn't crash?

    cell!.shouldEnableLikeButton(false)

    let liked: Bool = cell!.likeButton.selected
    cell?.setLikeStatus(liked)

    let originalButtonTitle = cell?.likeLabel!.text

    var likeCount: Int = originalButtonTitle!.toInt()! //This is where I get the error.. how can this be changed?

    if liked {
        likeCount += 1
    } else {
        likeCount -= 1
    }

    cell!.likeLabel.text = "\(likeCount)"
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Possible duplicate of [.toInt() removed in Swift 2?](http://stackoverflow.com/questions/30739460/toint-removed-in-swift-2) – Eric Aya Oct 20 '15 at 07:52

2 Answers2

1

You can unwrap it with if let by checking that your cell's title is convertible to Int or not this way:

let originalButtonTitle = cell.textLabel?.text

if let likeCount = Int(originalButtonTitle!) {   //Int(originalButtonTitle!) will convert your String to Int.
    let wrappedCount = likeCount
    print(wrappedCount)
}

Now it will not crash if any values are not convertible into Int from String.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0

toInt() function is deprecated in Swift2. Use:

if let likeCount = Int(originalButtonTitle)! {   
    let myVar = likeCount
}
Orkhan Alizade
  • 7,379
  • 14
  • 40
  • 79
  • Hi , i tried this but it's givingme an error "cannot find an initializer for type "int" that accepts an argument list of type '(string)' – suitescripter123 Oct 20 '15 at 05:26