[英]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
。 Double
和Int
不是兼容類型,因此無法編譯。
一個解決方法:
description += "\((operand - floor(operand) != 0) ? operand as AnyObject: Int(operand) as AnyObject)"
// now the two sides are both AnyObjects now!
如果您想要更少的重復代碼,就字符數而言,您可以將兩個操作數AnyObject
為Any
而不是AnyObject
。
description += String( (operand - floor(operand) != 0) ? operand : Int(operand) ).
此三元運算具有不同的結果類型,double 和 int。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.