According to Apple's documentation, Swift doesn't support preprocessor directives. In C/Objective-c the "INFINITY" definition is very useful for some checks. So, How do I get a number that never is less that another?
Asked
Active
Viewed 1.9k times
26
-
You could try dividing the float one by the float zero. – Pascal Cuoq Jun 04 '14 at 03:25
-
1@Pascal: That probably gets you the float NaN. Or a crash. – rickster Jun 04 '14 at 04:06
-
1@rickster I believe that the folk at Apple are a little more familiar with IEEE 754 than that. – Pascal Cuoq Jun 04 '14 at 05:42
-
@rickster, dividing by zero triggers an exception only with integer division. Edge case floating-point divisions are well-defined and do not cause CPU exceptions. – zneak Jun 04 '14 at 06:18
-
Swift does not support preprocessor directives, but thanks to the module implementation, Swift doesn't have to parse header files to have access to all what's inside. In fact, Swift *does* [translate simple macro values](https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_22) into global variables. I don't have access to the compiler, but have you tried simply using `INFINITY`? – zneak Jun 04 '14 at 06:29
-
@zneak I tried, but Xcode throw a error message "Use of unresolved identifier". Anyway, I am checking the "Simple Macros", that's very helpful, thanks. – Daniel Jun 04 '14 at 12:48
-
Using INFINITY directly results in an unresolved symbol error. I am using this homegrown formulae for dealing with 64-bit Doubles: unsafeBitCast(0x7ff << 52, Double.self) – John Difool May 26 '15 at 05:51
4 Answers
41
There is already buildin infinity and also a check function. And you could also directly compare them with <.
var infinity = Double.infinity
var isInfinite = infinity.isInfinite
var someDouble = 234432.0
if someDouble < infinity {
println("Less than")
} else {
println("Small than")
}
// And the answer is Less than.

sunkehappy
- 8,970
- 5
- 44
- 65
13
For integer values, you should use Int.max
.
var highestNumber = Int.max
//if you need negative infinity
var lowestNumber = Int.min
Using NSIntegerMax
instead of Int.max
or -1 * NSIntegerMax
instead of Int.min
is equivalent, but less pretty. (Thanks @Charlesism)

eLillie
- 653
- 9
- 17
0
Perhaps you can try finite
, for example,
let x:CDouble = 0.1
finite(x) // which return a CInt

shucao
- 2,224
- 1
- 13
- 7
0
For Float values,
import UIKit
typealias Space = Float
var MaxSpaceSize = Space.infinity
var space:Space = 1100
space = space * 2

Durul Dalkanat
- 7,266
- 4
- 35
- 36