【问题标题】:Swift: Cannot assign value of type 'int' to type 'string'Swift:无法将“int”类型的值分配给“string”类型
【发布时间】:2017-03-15 17:16:28
【问题描述】:

我有四个文本字段。一种是全浴,一种是四分之三浴,另一种是半浴,最后一种是四分之一浴。但是我转换成int后,还是报“无法转换int类型的值”的错误,代码如下。

HomeSingleton.sharedInstance3.HomeNumberOfFullBathstext = Int(Double(FullBaths.text!)! * 1.0) + Int(Double(Three_FourthsBaths.text!)! * 0.75) + Int(Double(One_HalfBaths.text!)! * 0.5) + Int(Double(One_fourthBaths.text!)! * 0.25)

【问题讨论】:

  • HomeNumberOfFullBathstext 是一个字符串,给它分配一个字符串而不是一个 int。
  • @john 将整个值分配给一个整数变量并获取您的输出,然后分配给 yourHomeSingleton.sharedInstance3.HomeNumberOfFullBathstext = String(your variable)
  • 它是一个字符串,因为 HomeNumberOfFullBathstext 是单例中的字符串,最后我会再次调用它并将该文本分配给 uilabel
  • @TusharSharma 你能告诉我怎么做吗
  • Var a: Int = Int(Double(FullBaths.text!)! * 1.0) + Int(Double(Three_FourthsBaths.text!)! * 0.75) + Int(Double(One_HalfBaths.text!) ! * 0.5) + Int(Double(One_fourthBaths.text!)! * 0.25) 之后 -: HomeSingleton.sharedInstance3。 HomeNumberOfFullBathstext = String(a) 。不确定它是否会工作尚未测试。

标签: ios iphone swift swift3


【解决方案1】:

错误消息显示所有内容。您需要将字符串值分配给 HomeNumberOfFullBathstext

HomeSingleton.sharedInstance3.HomeNumberOfFullBathstext = String(Int(Double(FullBaths.text!)! * 1.0) + Int(Double(Three_FourthsBaths.text!)! * 0.75) + Int(Double(One_HalfBaths.text!)! * 0.5) + Int(Double(One_fourthBaths.text!)! * 0.25))

【讨论】:

  • 问题是什么?
  • HomeNumberOfFullBathstext 仅显示 fullbaths.text 的文本,而不是所有添加在一起的内容
  • 它只返回整数,我试图返回小数。可能是什么问题
  • 四舍五入,我不知道为什么
  • 所以如果 0.5 是答案。 HomeNumberOfFullBathstext 将打印“0”
【解决方案2】:

也许使用:

HomeSingleton.sharedInstance3.HomeNumberOfFullBathstext = String(Int(Double(FullBaths.text!)! * 1.0) + Int(Double(Three_FourthsBaths.text!)! * 0.75) + Int(Double(One_HalfBaths.text!)! * 0.5) + Int(Double(One_fourthBaths.text!)! * 0.25))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多