Learn Swift From Objective-C : Variables, Classes, Methods and Properties

In this article series, we’re going to look at some of the differences between Swift and Objective-C. This tutorial is best suited for people who already know Objective-C (at least the basics) and want to see what the equivalents are in Swift.

If you’re a non-programmer and you’re just beginning your journey into iOS development, I’d recommend taking a look at my course where you’ll learn Swift as part of learning how to build iPhone apps.

Ok, so lets get into it! This is a handy language guide to keep around as you’re learning Swift.

Variables and Constants

Swift makes declaring variables less confusing for beginners because it sounds more like natural language. Also note that you no longer put a semi-colon to end a statement.

Declaring an int variable

Objective-C

In Objective-C, you always have to explicitly specify the type of variable you’re declaring.

int highScore;
NSString *playerName;

Swift

In Swift, the “var” keyword is used to declare a variable and you don’t have to specify the type if it can be inferred from what you’re assigning it. Also notice in Swift, we’re using the String class as opposed to NSString.

var highScore: Int

var playerName: String

Assigning to a variable

Notice that when creating a string literal to assign to the string variable, we don’t need the “@” for Swift.

Objective-C

highScore = 1000;
playerName = @"Joe Chan";

Swift

highScore = 1000
playerName = "Joe Chan"

Declaring and assigning constants

In Swift, use the let keyword to declare constants.

Objective-C

NSString *const skyColor = @"Blue";
int const daysInYear = 365;

Swift

let skyColor = "Blue"

let daysInYear = 365

Classes

Defining a class

A notable difference in class definition with Swift is the absence of the header (.h) and implementation (.m) file.

Objective-C

A header (.h) file

@interface CustomClass : NSObject
@end

An implementation (.m) file

@implementation CustomClass
@end

Swift

class CustomClass {
}

Creating a new class instance

Creating new classes in Swift is done with the classname followed by a pair of parentheses.

Objective-C

CustomClass *instance = [[CustomClass alloc] init];
CustomClass *secondInstance = [CustomClass new];

Swift

var instance = CustomClass()

Subclassing

Subclassing is very similar in both languages.

Objective-C

In the header (.h) file

@interface SpecificCar : Car
@end

Swift

class SpecificCar : Car {
}

Methods

Declaring a method

Declaring a method is easier for beginners to understand as well. Notice in the Swift example how the return type of the method is specified.

Objective-C

In the header (.h) file

- (int) getOdometerReading;

In the implementation (.m) file

- (int) getOdometerReading
{
   return 50000;
}

Swift

func getOdometerReading() -> Int {
        return 50000
}

Calling a method

Often, beginners are confused as to when to use square brackets. Swift does away with the square brackets for calling methods and instead uses the dot-notation we’re accustomed to seeing with properties. Notice the parentheses in the Swift example for calling a method.

Objective-C

SpecificCar *myCar = [[SpecificCar alloc] init];
[myCar getOdometerReading];

Swift

var myCar = SpecificCar()
myCar.getOdometerReading()

Declaring a method with multiple parameters

A Swift method with multiple parameters is similar to Objective-C in the way that it’s structured in pairs of label:parametername

Objective-C

- (void)changeEngineOil:(int)oil transmissionFluid:(int)fluid
{
}

Swift

func changeEngineOil(oil:Int, transmissionFluid:Int) 
{
}

Calling a method with multiple parameters

Objective-C

[myCar changeEngineOil:10 transmissionFluid:10];

Swift

myCar.changeEngineOil(10, transmissionFluid:10)

Overriding a method

In Objective-C, you can override a method of the super class by just defining a method with the same method signature in the subclass. In Swift however, we have to explicitly put the override keyword so that it’s clear that it’s an overridden method.

Objective-C

In the implementation (.m) file

- (void)someMethod
{
   [super someMethod];
   // Additional overridden behavior below
}

Swift

override func someMethod() 
{
    super.someMethod()
    // Additional overridden behavior below
}

Properties

Declaring a property

Declaring properties with Swift is pretty straight forward. In fact, it looks just like declaring a variable except where you declare it is what makes is a property. In Swift, every property needs to be assigned a value either during declaration or in the initializer.

Objective-C

In the implementation (.m) file

@interface SpecificCar ()

@property NSString *transmission;
@property int numberOfSeats;

@end

@implementation SpecificCar

- (id)init
{
    self = [super init];
    if (self)
    {
        self.transmission = @"Automatic";
        self.numberOfSeats = 4;
    }
    return self;
}

@end

Swift

class Specific:Car {
   var transmission: String = "Automatic"
   var numberOfSeats: Int

   init() 
   {
       self.numberOfSeats = 4
       super.init()
   }
}

Overriding the getter and setter

In modern Objective-C, the getter and setters are automatically synthesized for you but you can override them. The same is true for Swift and the syntax is a little easier on the eyes because it’s grouped together with the declaration.

Objective-C

- (void)setTransmission:(NSString *)transmission
{
    _transmission = transmission;
}

- (NSString *)transmission
{
    return _transmission;
}

Swift

var transmission: String {
    get {
        return _transmission
    }
    set {
        _transmission = newValue
    }
}

What’s Next

In the next part of the series, we’ll look into the Swift equivalents of some Objective-C control structures and collections.

12 Comments

  1. Chris, when you are going to release part 3, i.e protocols and delegates ? Liked your blog very much for learning swift in comparison with Objective c.

    Reply
  2. Please make sure your examples are syntactically correct. I can see a few mistakes where you might have made a quick copy-paste error. You also missed a * on a NSString declaration. This is trivial to the experienced person, but *fatal* to the newbie. 🙂

    Reply
  3. Thanks for covering Swift, Chris! Coming from a Java background, this new syntax is such a relief! The syntax of Objective-C was one of the main things that inhibited my learning.

    Reply
  4. So in swift there are no header and implementation files? and are all variables created outside methods instance variables?

    Reply
  5. The fact that Swift handles the alloc/init part is a good thing for beginners!
    I’m glad about a few stuff but… I’m gonna have to put my studies on those inout, get/set, wilt/willset, closure and functions.

    Reply

Leave a Reply to Joel Cancel reply

47 Shares
Share
Tweet
Pin
Share
Buffer