在 Swift 中使用三元运算符将 Double 转换为 String

Converting Double to String with ternary operator in Swift

在 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) )

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

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

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

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

在您的代码中,

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

: 的左侧是 Double,而右侧是 IntDoubleInt 不是兼容类型,因此无法编译。

解决此问题的方法:

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

如果你想要更少的重复代码,在字符数方面,你可以将两个操作数转换为Any而不是AnyObject