【问题标题】:Warning message for String only unwraps optionalsString 的警告消息仅解开选项
【发布时间】:2019-08-11 01:29:56
【问题描述】:
let condition = (priceModel?[indexPath.row].changePercentage as! String)

警告信息:

从“字符串?”强制转换to 'String' 只解开选项;您的意思是使用“!”吗?

如何清除警告信息?

【问题讨论】:

  • changePercentage 已经是一个字符串。所以如果你还想强制解包,.changePercentage as! String => .changePercentage!.
  • 考虑将priceModel 声明为非可选空数组。这样可以避免那些恼人的错误。
  • Xcode 中的这个警告不应该像下面的答案那样建议代码更改吗?
  • 你不需要投射as! String,但你需要解开它。

标签: swift


【解决方案1】:

这意味着你需要使用

(priceModel?[indexPath.row].changePercentage)!

当施法力用于相同类型时使用!因为类型已经是 String 所以!as! String 更有意义

let condition = priceModel![indexPath.row].changePercentage 

假设changePercentage 不是可选的

【讨论】:

    【解决方案2】:

    我建议使用if 语句来避免强制解包。

    if let condition = priceModel?[indexPath.row].changePercentage as? String {
       // the rest of your code
    }
    

    【讨论】:

      【解决方案3】:
      let condition = (priceModel?[indexPath.row].changePercentage)!
      

      虽然如果它为 nil 可能不安全

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-19
        • 1970-01-01
        相关资源
        最近更新 更多