繁体   English   中英

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

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

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

在您的代码中,

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

的左侧:是一种Double ,而右侧是一个Int DoubleInt不是兼容类型,因此无法编译。

一个解决方法:

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

如果您想要更少的重复代码,就字符数而言,您可以将两个操作数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