Skip to content

Overview_SwiftObjC_similarities

Tom Ryan edited this page Jun 2, 2015 · 3 revisions

Doing the things you normally do in Objective-C the Swift way

Thanks to the awesome (cough cough) code completion in Xcode, in most cases you'll know how to most things you need to do. There are, however, sometimes different ways of accomplishing things you need to do.

Categories and Extensions

Objective-C: Categories

Adding functionality to existing classes (either your own, or classes belonging to an existing framework) in Objective-C is done by creating a category.

Person+Extras.h

@interface Person (Extras)
- (NSString *)fullName;
@end

Person+Extras.m

@implementation Person (Extras)
- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}
@end
Swift: Extensions

Adding functionality to existing classes or structs (either your own, or those belonging to an existing framework) in Swift is done by creating an extension.

PersonExtension.swift

extension Person {
    func fullName() -> String {
        return "\(self.firstName) \(self.lastName)"
    }
}

Note that in both Objective-C and Swift, these need not be in a separate file, but for extensive changes, should be.

Objective-C

The recommended way of ensuring your object can be determined to be equal to another instance is to override the following:

- (BOOL)isEqual;
- (NSUInteger)hash

Take a look at the NSHipster article for a fuller definition of how to go about doing this.

Swift

In Swift, the == operator needs to be declared **at the base scope of the project (that is, outside of the class/struct declaration). == can be overridden multiple times, as long as the lhs and 'rhs' argument types are unique.

func ==(lhs: TutorialStruct, rhs: TutorialStruct) -> Bool {
    return lhs.firstVariable == rhs.firstVariable
}