【问题标题】:Converting Double to String with ternary operator in Swift在 Swift 中使用三元运算符将 Double 转换为 String
【发布时间】:2017-01-17 22:07:38
【问题描述】:

在 swift 中使用双精度时需要消除额外的零,例如(3.0 应该像 3 一样输出,3.2 应该是 3.2)

//description is String; operand is Double

// works
(operand - floor(operand) != 0) ? (description += String(operand)) : (description += String(Int(operand)))

// not works
description += String( (operand - floor(operand) != 0) ? operand : Int(operand) )

为什么三元运算符在第二个版本中会出错?有没有其他方法可以避免重复代码?

【问题讨论】:

  • 当您发布有关错误的问题时,您需要在问题中包含完整且准确的错误。

标签: swift ternary-operator


【解决方案1】:

关于使用三元运算符有很多规则。其中之一是:字符左右两边的操作数必须是兼容的类型。

在您的代码中,

(operand - floor(operand) != 0) ? operand : Int(operand)

: 的左侧是Double,而右侧是Int。 Double 和 Int 不是兼容类型,所以编译失败。

解决方法:

description += "\((operand - floor(operand) != 0) ? operand as AnyObject: Int(operand) as AnyObject)"
// now the two sides are both AnyObjects now!

如果您想要更少的重复代码,就字符数而言,您可以将两个操作数强制转换为Any 而不是AnyObject。

【讨论】:

    【解决方案2】:
    description += String( (operand - floor(operand) != 0) ? operand : Int(operand) ). 
    

    这个三元运算有不同的结果类型,double 和 int。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-25
      • 2022-07-07
      • 2019-10-26
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多