Moving Swiftly

It's been three weeks since Apple has announced their new programming language, Swift, to the world. I, like the other 6000+ developers live at the Moscone Center for WWDC 2014, was one of the first developers (outside of Apple) to begin coding programs in Swift. If your haven't heard of Swift, or would like to learn more, check out Apple's Introducing Swift.

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.

swift-playground As self-taught iOS engineer, not from a computer science background, I found a small amount of the abstractions and translations from Objective-C to Swift troublesome. I hope that the snippets I post below will help someone stuck on an issue with not enough resources to go off of until Apple finishes the documentation.

Singletons

Objective-C:

+ (InstanceType *)shareInstance
{
    static InstanceType *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[InstanceType alloc] init];
    });
    return instance;
}

Swift:

let instance = InstanceType()

class InstanceType {  
    class var sharedInstance: InstanceType {
        return instance
    }
}

Blocks (Closures)

Objective-C:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  
manager.requestSerializer = [AFJSONRequestSerializer serializer];  
manager.responseSerializer = [AFJSONResponseSerializer serializer];  
[manager GET:<URL> parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Do something.
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // Do something.
    }];

Swift:

let manager = AFHTTPRequestOperationManager()        manager.requestSerializer = AFJSONRequestSerializer()  
manager.responseSerializer = AFJSONResponseSerializer()  
manager.GET(<URL>,  
    parameters: nil,
    success: { [weak self] (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
      // Do something.
            },
            failure: { [weak self] (operation: AFHTTPRequestOperation!, error: NSError!) in
      // Do something.
            })

Comments