简体   繁体   English

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

[英]Swift: Cannot convert from string to int (using slider tag)

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

I get an error from the above: Cannot assign value of type 'String?' 我从上面收到错误: 无法分配类型为'String'的值? to type 'Int' 输入“ Int”

This doesn't work (below): 这不起作用(如下):

cell.slider.tag = Int(deviceTag)

or what "fix-it" provides: 或“修复”提供的内容:

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

You need to set optional while casting from string. 从字符串强制转换时,您需要设置可选参数。 Try the below code. 试试下面的代码。

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

Unless you're 100% sure the value of the dictionary device is an Int you shouldn't implicitly unwrap those optionals. 除非您100%确信字典device的值是一个Int,否则您不应该隐式解开那些可选内容。

You can use: 您可以使用:

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

or 要么

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

But looking at your examples, it seems like deviceTag isn't a number at all. 但是从您的示例deviceTag似乎deviceTag不是数字。 Perhaps you should look in your debug area (left panel) to see what the value is or simply print(deviceTag) to see what the value is. 也许您应该在调试区域(左侧面板)中查看该值是什么,或者只是在print(deviceTag)中查看该值是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM