Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 致命错误:从字符串转换为INT时展开可选值_Ios_Swift - Fatal编程技术网

Ios 致命错误:从字符串转换为INT时展开可选值

Ios 致命错误:从字符串转换为INT时展开可选值,ios,swift,Ios,Swift,您好,我正在尝试在下面的代码中将字符串转换为Int:如何更改下面将字符串转换为Int的代码,使应用程序不会崩溃 cell!.shouldEnableLikeButton(false) let liked: Bool = cell!.likeButton.selected cell?.setLikeStatus(liked) let originalButtonTitle = cell?.likeLabel!.text var likeCount: I

您好,我正在尝试在下面的代码中将字符串转换为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)"
toInt()
函数在Swift2中不推荐使用。使用:

if let likeCount = Int(originalButtonTitle)! {   
    let myVar = likeCount
}

通过检查单元格标题是否可转换为
Int
,您可以使用if-let将其展开:

let originalButtonTitle = cell.textLabel?.text

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

现在,如果任何值不能从
String

转换为
Int
,它将不会崩溃。嗨,我尝试了这个方法,但它给我一个错误“找不到类型为“Int”的初始值设定项,该初始值设定项接受类型为“(String)”的参数列表,可能重复