您好我在下面的代码中尝试将字符串转换为Int:如何更改以下将字符串转换为Int的代码,以便应用程序不会崩溃?
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)"
答案 0 :(得分:1)
你可以通过检查你的手机的标题是否可以转换为Int
来解开它:
let originalButtonTitle = cell.textLabel?.text
if let likeCount = Int(originalButtonTitle!) { //Int(originalButtonTitle!) will convert your String to Int.
let wrappedCount = likeCount
print(wrappedCount)
}
现在,如果任何值无法从Int
转换为String
,则不会崩溃。
答案 1 :(得分:0)
toInt()
函数。使用:
if let likeCount = Int(originalButtonTitle)! {
let myVar = likeCount
}