简体   繁体   中英

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)

//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 and Int are not compatible types, so it fails to compile.

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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