Converting Complex Expressions with Swiftify

Converting code is hard enough. Why run the risk of missing a crucial condition in a long if-statement? Or running into floating point errors caused by using the wrong numeric types?

The latest release of the Swiftify Objective-C to Swift converter handles converting complex expressions so you don’t have to. These are some of the complex cases we’ve handled:

Explicit Type Conversion for Numerics

In Objective-C, you can perform operations on two different numeric types. For instance, adding a double to a float:

double d = 1.0;
float f = 2.0;
double d2 = d + f;

In Swift, you need to be more explicit. A Double can’t interact with a Float directly. First, the operands need to be explicitly cast:

let d: Double = 1.0
let f: Float = 2.0
let d2: Double = d + Double(f)

You can test the conversion here: http://swiftify.me/mawt4g

Unwrapping Optional Boolean Conditions

In Swift, a Bool is not the same as an Optional<Bool>. For instance, converting this:

NSData *myData;
BOOL hasData = myData.length > 0;
if (hasData) {
NSLog(@"Handle data");
}

to this:

var myData: Data?
var hasData: Bool? = myData?.length > 0
if hasData {
print("Handle data")
}

hasData becomes an optional Bool because myData is an optional Data. The conversion won’t compile because hasData is neither true or false. It’s just Optional.none.

Swiftify now handles the conversion like this:

var myData: Data?
var hasData: Bool = (myData?.count ?? 0) > 0
if hasData {
print("Handle data")
}

hasData is ensured to never be optional, and the example will compile. Try it out! http://swiftify.me/1f4olc

Comparing Optionals to Nil

Consider this alternative to the previous example:

NSData *myData;
if (myData && myData.length > 0) {
NSLog(@"Handle data")
}

If myData exists and has a length greater than 0, we log a message.

In Objective-C, you can treat myData as a Boolean by using if (myData). But, you guessed it, Swift needs you to be more explicit! A direct conversion won’t compile:

var myData: Data?
if myData && (myData?.count ?? 0) > 0 {
print("Handle data")
}

You need to compare myData to nil directly. Here’s the new output from Swiftify:

var myData: Data?
if myData != nil && (myData?.count ?? 0) > 0 {
print("Handle data")
}

Which compiles as expected. Try it out: http://swiftify.me/url137

Seen anything in the wild?

What other complex examples have you seen? Let us know. Once it’s automated by Swiftify, you don’t have to worry about it!