Learn Swift from Objective-C : Conditionals, Control Structures and Collections

This tutorial is a continuation from Part 1 where we went through a comparison between Swift and Objective C for various operations involving variables, classes, methods and properties. 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… View Article
Written by

Chris C

Updated on

Sep 24 2019

Table of contents

    This tutorial is a continuation from Part 1 where we went through a comparison between Swift and Objective C for various operations involving variables, classes, methods and properties.

    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.

    Control Flow

    Writing an IF statement

    Objective-C

    Notice in the second example that the If statement tests if the variable “aString” is empty.

    int score = 25;
    if (score > 25) {
    }
    
    NSString *aString;
    if (aString) {
    }
    

    Swift

    In Swift, we need to denote that a variable has an optional value with a question mark. This means that it could be empty.
    Then we use the let keyword and a name to test if aString is empty.

    var score = 25
    if score > 25 {
    }
    
    var aString: String?
    if let myString = aString {
    }
    

    Writing a Switch statement

    In Swift, switch statements are a lot more flexible and can be used to test a variety of comparison operations. In Objective-C, switch statements were limited to integer cases.

    Objective-C

    int numberOfPeople = 1;
    
    switch (numberOfPeople)
    {
        case 1:
            // code for this case
            break;
        case 2:
            // code for this case
            break;
        default:
            // code for this case
            break;
    }
    

    Swift

    Notice that you don’t need the break statements anymore!

    var numberOfPeople = 1
    
    switch numberOfPeople {
        case 1:
            // code for this case
        case 2:
            // code for this case
        default:
            // code for this case
    }
    
    var carMake = "Toyota"
    
    switch carMake {
        case "Toyota":
            // code for this case
        case "Honda":
            // code for this case
        case "Nissan", "Subaru":
            // code for this case
        default:
            // code for this case
    }
    

    Loops

    Writing a For loop

    Objective-C

    for (int i = 0; i < 10; i++) {
    }
    
    NSArray *array = @[@"item 1", @"item 2"];
    for (NSString *item in array) {
    }
    

    Swift

    Notice the second swift example below. It’s equivalent to the first example. The .. notation can signify a range.

    for var i = 0; i < 10; i++ {
    }
    
    for i in 0..10 {
    }
    
    var array = ["item 1", "item 2"]
    for item in array {
    }
    

    Writing a while or do while loop

    The while loop syntax in Swift is almost identical to Objective-C (the Swift syntax drops the parentheses).

    Objective-C

    int count = 1;
    while (count < 10) {
        count++;
    }
    
    do
    {
        count++;        
    } while (count < 10);
    

    Swift

    var count = 1
    while count < 10 {
        count++
    }
    
    do
    {
        count++
    } while count < 10
    

    Collections

    Declaring an array

    Arrays in Objective-C used the NSArray and NSMutableArray classes and each array could contain a mixture of objects of different class types. In Swift, there’s one Array class and you have to specify the type of objects that the array will contain.

    Objective-C

    NSMutableArray *myArray = [[NSMutableArray alloc] init];
    
    NSMutableArray *myArray2 = [@[@"item 1", @"item 2"] mutableCopy];
    

    Swift

    Notice that in the second and third examples, we don’t specify that the variable is of type String Array uses because it can be inferred from the array that we’re assigning it. From the assigned array items, Swift can infer that the variable is an Array and it contains String objects.

    Even in example 1, we don’t need to specify the variable type because it can be inferred from what we’re assigning to it.

    var myArray:[String] = [String]()
    
    var myArray2 = ["item 1", "item 2"]
    

    Adding and inserting into an array

    Objective-C

    myArray[0] = @"item 1";
    
    [myArray addObject:@"item 3"];
    
    [myArray insertObject:@"item 4" atIndex:1];
    

    Swift

    Notice in the second example that you can use += to append objects into the array.

    myArray[0] = "item 1"
    
    myArray.append("item 3")
    myArray += "item 3"
    
    myArray.insert("item 4", atIndex:1)
    
    

    Declaring a dictionary

    Just like Arrays in Swift, Dictionaries need to be type safe so you have to define what class types the dictionary is going to use for its keys and values.

    Objective-C

    NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
    
    NSMutableDictionary *myDictionary2 = [@{@"key":@"object", @"key2":@"object 2"} mutableCopy];
    

    Swift

    var myDictionary = Dictionary<string, string="">()
    
    var myDictionary2 = ["key":"object", "key2":"object 2"]
    </string,>

    Adding and Assigning to a dictionary

    Assigning to a dictionary in Swift is very similar to Objective-C.

    Objective-C

    [myDictionary setObject:@"object 3" forKey:@"key3"];
    
    myDictionary[@"key2"] = @"object 4";
    

    Swift

    Notice in Swift, you can use the same syntax to add a key/value pair or reassign an object for a particular key.

    myDictionary["key3"] = "object 3"
    
    myDictionary["key2"] = "object 4"
    

    What’s Next

    In the next part of the series, we’ll look at protocols and delegation in swift!



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris
    9 Shares
    Share
    Tweet
    Pin
    Share
    Buffer