Swift:无法从字符串转换为int(使用滑块标记)

时间:2016-01-22 07:26:39

标签: ios string swift int

let device = devices[indexPath.row]
let deviceTag = device["deviceID"] as? String
cell.slider.tag = deviceTag

我从上面得到一个错误:无法分配'String'类型的值?输入'Int'

这不起作用(下面):

cell.slider.tag = Int(deviceTag)

或“fix-it”提供的内容:

cell.slider.tag = Int(deviceTag!)!

2 个答案:

答案 0 :(得分:1)

您需要在从字符串转换时设置可选项。请尝试以下代码。

let device = devices[indexPath.row]
let deviceTag = device["deviceID"] as! String
cell.slider.tag = Int(deviceTag)

答案 1 :(得分:1)

除非你100%确定字典device的值是一个Int,否则你不应该隐式地打开这些选项。

您可以使用:

if let deviceTag = deviceTag, tag = Int(deviceTag) { cell.slider.tag = tag }

cell.slider.tag = Int(deviceTag) ?? 0

但是看看你的例子,似乎deviceTag根本不是一个数字。也许您应该查看调试区域(左侧面板)以查看值是什么,或者仅查看print(deviceTag)以查看值是什么。