简体   繁体   English

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

[英]Converting Double to String with ternary operator in Swift

Need to eliminate extra zeros when working with doubles in swift eg (3.0 should output like 3 and 3.2 should be 3.2)在 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) )

Why ternary operator is giving an error in second version?为什么三元运算符在第二个版本中出错? Is there any other way to avoid duplicate code?有没有其他方法可以避免重复代码?

There are a lot of rules regarding using the ternary operator.关于使用三元运算符有很多规则。 One of them is that the operand on the left and right side of the : character must be of compatible types.其中之一是:字符左右两侧的操作数必须是兼容的类型。

In your code,在您的代码中,

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

The left side of the : is a Double , while the right side is an Int .的左侧:是一种Double ,而右侧是一个Int Double and Int are not compatible types, so it fails to compile. DoubleInt不是兼容类型,因此无法编译。

A workaround for this:一个解决方法:

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

If you want even less duplicate code, in terms of number of characters, you can cast the two operands to Any instead of AnyObject .如果您想要更少的重复代码,就字符数而言,您可以将两个操作数AnyObjectAny而不是AnyObject

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

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

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

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