#

Lost In Translation

#

It's tough pivoting between any two languages, nonetheless, two languages that are eerily similar yet very very unique. Some could use this paradox for spoken languages such as Latin, Greek, Spanish and French, etc. But today, I am discussing the relaying of messages between the syntax of Objective-C and that of Apple's new Swift language.

How to declare blocks in Objective-C:

As a local variable:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};  

As a property:

@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

As a method parameter:

- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;

As an argument to a method call:

[someObject someMethodThatTakesABlock: ^returnType (parameters) {...}];

As a typedef:

typedef returnType (^TypeName)(parameterTypes);  
TypeName blockName = ^returnType(parameters) {...};  

How to declare closures in Swift:

As a variable:

var closureName: (parameterTypes) -> (returnType)  

As a type alias:

typealias closureType = (parameterTypes) -> (returnType)  

As a constant:

let closureName: closureType = {...}  

As an argument to a function call:

func ({(parameterTypes) -> (returnType) in statements})  

As a function parameter:

array.sort({ (item1: Int, item2: Int) -> Bool in return item1 < item2 })  

As a function parameter with implied types:

array.sort({ (item1, item2) -> Bool in return item1 < item2 })  

As a function parameter with implied return type:

array.sort({ (item1, item2) in return item1 < item2 })  

As the last function parameter:

array.sort { (item1, item2) in return item1 < item2 }  

As the last parameter, referred to by numbers*:

array.sort { return $0 < $1 }  

As the last parameter, with an implied return value:

array.sort { $0 < $1 }  

How to declare singletons in Objective-C:

Implementation:

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

Usage:

InstanceType *instanceType = [InstanceType sharedInstance];  

How to declare singletons in Swift:

Implementation:

class InstanceType {  
    class var sharedInstance : InstanceType {

        struct Static {
            static let instance : InstanceType = InstanceType()
        }

        return Static.instance
    }
}

Usage:

let instanceType = InstanceType.sharedInstance  

Comments