-
Notifications
You must be signed in to change notification settings - Fork 3
Overview_SwiftObjC_similarities
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.
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
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.
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.
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
}