var arr1: Array = [34, 8.7, "hello"]
var arr2: Array<Any> = [34, 8.7, "hello"]
println(arr1)
println(arr2)
[34, 8.699999999999999, hello] [34, 8.7, hello]
different result,anyone can explain it?
In the case of arr1, since you didn't specify the type and you have Foundation imported, Swift made the array type [NSObject]. Then, the types of 34, 8.7, and "hello" are NSNumber, NSNumber, and NSString respectively.
For whatever reason, an NSNumber with a value of 8.7 prints as 8.699999999999999. Try this is a Playground:
var a: NSNumber = 8.7
println(a) // prints 8.699999999999999
In arr2, the values have the types Int, Double, and String, so the 8.7 prints as you would expect:
var b: Double = 8.7
println(b) // prints 8.7
As Matt Gibson states in the comments:
the output difference may be because NSNumber's description method formats the number as "%0.16g"; if you do NSString(format: "%0.16g", 8.7) gives you "8.699999999999999". I'm sure they're both just the same double "underneath".
To test the theory that they are the same number underneath, I did:
if (arr1[1] as NSNumber).doubleValue == (arr2[1] as Double) {
println("same")
}
and this does indeed print "same".
description method formats the number as "%0.16g"; if you do NSString(format: "%0.16g", 8.7) gives you "8.699999999999999". I'm sure they're both just the same double "underneath".
println(NSNumber(double: 8.7))andprintln(Double(8.7))give different results?"