So, let me guess, you’ve been an iOS developer for a while working with Objective-C and you are good at it, you don’t want to use anything else for your applications and you can not imagine your life without putting your code inside brackets.

If that’s the case this blog post is for you. As you know, Swift is becoming more and more popular these days and recruiters and companies are requiring developers that know this language more often.

Here is a short mix between some topics that I’ve been asked in past interviews and some others that will help make the transition to Swift from Objective-C a little bit easier.

1 — What is the difference between structs and classes?

One of the most important differences between structures and classes is that structures are value types and are always copied when they are passed around in your code, and classes are reference type and are passed by reference. Also, classes have Inheritance which allows one class to inherit the characteristics of another.

2 — What is the difference between value types and reference types?

To extend the answer about the difference between structs and classes is necessary to understand the difference between value and reference types,

When you make a copy of a value type, it copies all the data from the thing you are copying into the new variable. They are 2 separate things and changing one does not affect the other.

When you make a copy of a reference type, the new variable refers to the same memory location as the thing you are copying. This means that changing one will change the other since they both refer to the same memory location.

if it’s still not clear, here is an example

3 — What does the keyword “mutating” means in Swift?

We can’t directly chang the value of a value type inside its implementation, it can only be possible when a copy is created and we assign the value that we want to the new copy. However, if we want to change a value type inside the implementation we can use the “mutating” keyword before the function declaration.It indicates that the method will modify the struct’s values allowing the compiler to create a copy of the struct.

Here is a code example

4 — What do the “static”, “class”, “final” keywords mean in Swift type methods?

In type methods these keywords mean:

static: in value types, structs for example, this keyword mean that a method is associated at the type level rather than an instance. In reference types, it also means that the method is associated at the type level of the class but it also doesn’t allow that this method can be overriden for a subclass.

class: is how you create class methods in objective C, and they can be overriden by a subclass.

final: it’s an alias for static in methods, but you can also use it before the declaration of a class to make it immutable.

For classes, in general always use “static” to create type methods, the only time you should use “class” keyword is if your subclass really needs to override it.

Here is an example in code.

5 — What are optionals in Swift?

In many languages, when you encounter the absence of data, you have to deal with it by writing another path for your code. There is no indication that the data doesn’t exist so at many points in your program you have to write defensive code. This isn’t the situation in Swift, and optional types are how Apple handles the absence of data in an application.

For more about optionals, go here

6 — What is let and var in Swift?

In Swift, var means variable. A variable is an object that can be mutated, or changed. On the other hand, let means constant and means that the value assigned to the object can never be changed. Once it is set, it’s done. You use a constant when you need to set a value that will never change.

For more details go here

7 — What are tuples in Swift?

Tuples are simply ordered sets of values and for our purposes, they group multiple values into a single compound value.

Why is this important? In Objective-C, if you want a method to return more than one value you have two options — return a custom object with properties that store your return values or stick those values in a dictionary. With Swift however, we can use tuples to return more than one value. The values in a tuple can be of any type and don’t have to be the same type as each other.

For example ("Sasha", "Blumenfeld") holds the first and last name of a person. You can access the inner values using the dot( . ) notation followed by the index of the value:

var person = ("Sasha", "Blumenfeld") var firstName = person.0 // Sasha

var lastName = person.1 // Blumenfeld

Named elements

You can name the elements from a tuple and use those names to refer to them. An element name is an identifier followed by a colon(:).

var person = (firstName: "Sasha", lastName: "Blumenfeld") var firstName = person.firstName // Sasha

var lastName = person.lastName // Blumenfeld

Creating a tuple

You can declare a tuple like any other variable or constant. To initialize it you will need an another tuple or a tuple literal. A tuple literal is a list of values separated by commas between a pair of parentheses. You can use the dot notation to change the values from a tuple if it’s declared as a variable.

var point = (0, 0) point.0 = 10

point.1 = 15 point // (10, 15)

Note: Tuples are value types. When you initialize a variable tuple with another one it will actually create a copy.

var origin = (x: 0, y: 0)

var point = origin

point.x = 3

point.y = 5 print(origin) // (0, 0)

print(point) // (3, 5)

For more about tuples visit this link

8 — In Swift error handling what does the keywords try, catch, do , guard and throws keywords mean?

If you are new in Swift you definitely saw these keywords in different code samples. These keywords are in charge to handle errors in applications. This is a super cool topic and I recommend to go to the documentation to understand them, let me share some of my thoughts.

When you use “do” you are saying to your code to execute a certain action inside the do statement, that is potentially insecure. You can use the “try” method if the implementation can throw an error, and the catch statement finally will catch that error if exists.

Guard is like optional binding but with an external variable, this ends in an else clause where you can handle errors.

Throws, you add this keyword before your return type in a function when the execution of this method is potentially insecure.

I attached some code for you here.

9 -In Swift what are computed properties?

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

Here is a detailed example

10 — In Swift, what are failable and throwing initializers?

Very often initialization depends on external data, this data can exist as it can not, for that Swift provides two ways to deal with this.

Failable initializers return nil of there is no data, and let the developer “create” a different path in the application based on that.

In other hand throwing initializers returns an error on initialization instead of returning nil.

Here is an example.

11 — What is an extension in Swift, how could you use it?

If you have experience with Objective-C, you probably can find extensions similar to categories.

In Swift, you can use Extensions to add new functionality to existing classes, structs, and enumeration types. They are also used to improve readability and to make an existing type conform a protocol.

Plus, extensions provide default implementations for a protocol.

Here is an example.

12 — In an enum what are raw and associated values?

Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e.

let A = 0

let B = 1

is similar to:

enum E: Int {

case A // if you don't specify, IntegerLiteralConvertible-based enums start at 0

case B

}

So, A has a fixed raw value of 0 , B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case). They can only be literal-convertible strings, characters or numbers. And they all have to be distinct (no two enums can have the same raw value).

Associated values are more like variables, associated with one of the enumeration cases:

enum E {

case A(Int)

case B

case C(String)

}

Here, A now has an associated Int that can hold any integer value. B on the other hand, has no associated value. And C has an associated String . Associated types can be of any type, not just strings or numbers.

Any given value of type E will only ever hold one of the associated types, i.e. either an Int if the enum is an A , or a String if the enum is a C . It only needs enough space for the bigger of the two. Types like this are sometimes referred to as "discriminated unions" – a union being a variable that can hold multiple different types, but you know (from the enum case) which one it is holding.

They can even be generic. The most common example of which is Optional , which is defined like this:

enum Optional<T> {

case .Some(T)

case .None

}

from Stackoverflow

13 — In Swift what are type aliases?

Swift comes with two type aliases to represent non-specific types “Any” and “AnyObject”.

AnyObject represents an instance of any class type and Any is the most generic representation of a type in Swift, it can represent an instance of absolutely any type including functions.

14 — In Swift what are designated and convenience initializers?

Designated initializers are:

The CENTRAL point of initialization of a class.

Classes MUST have at least one.

Is the responsible for initializing stored properties.

Is the responsible for calling super init.

Convenience initializers are:

SECONDARY supporting initializers for a class.

It can only call a designated initializer that is defined in the same class

It can also call another convenience initializers defined in the same class

They are not required, that sort of implied. they are just initializers that we can write for a CONVENIENCE use case

In a class, They use the keyword “convenience before the init keyword.

Finally here are 3 basic rules of class initialization:

Every class must have a designated initializer, if this class inherits from another, the designated initializer is responsible for calling the designated initializer of its immediate superclass.

Classes can have any number of convenience initializers, a convenience initializer must call another initializer from the same class, whether it is a designated initializer or another conveniences initializer.

Convenience initializers must ultimately call a designated initializer.

Here is a code example

15 — What does the “required” keyword mean in Swift?

Sometimes we could want all subclasses of a particular superclass to implement a certain initializer. By adding “required” to an init method, we’re indicating that all subclasses must provide an implementation for this particular init method. Also if you define an initializer method in a protocol when you are conforming types implemented, it is also marked as required initializer.

16 — In swift what does array homogeneity rule stands for?

This means that in Swift all the items inside an array must be of the same type, in order to preserve this Swift casts different subclasses to the brace class.

For example.

17 — In Swift, what is Access Control?

Access control restricts access to parts of your code from code in other source files and modules. This feature enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.

There are 5 access levels:

Open .- Is the highest access level or the least restrictive access level. You can subclass classes marked as open.

Public .- Open and public enable code written in a source file to be used anywhere within a module as well as from another module that imports it. You can use classes marked with Public but you can’t subclass them.

Internal.- Enables entities to be used within any source file from their defining module, but not in any source file outside of the module. This is the default level of access.

Fileprivate. — Allows you to restrict the use of an entity within its defining source file.

Private.- Is the most restrictive access level. This means that the use of an entity is restricted to an enclosing declaration. For example, a private stored property can only be used within its class.

Access Control is most useful in two particular cases when you are writing frameworks or writing tests.

Finally, it’s very important to know that you can not define an entity in terms of another entity that has a lower or more restrictive access level.

18 — When should a property be strong vs weak?

By default any references to an object are strong, to help combat the reference cycles that may arise, ARC also allows for “weak” references, a weak reference is one that does not keep a strong hold on the instance it refers to. And doesn’t stop ARC from disposing of it.To use it we add the weak keyword to our store property declaration interface builder outlets, are created as weak stored properties by default, this is because of view controllers maintain a reference to the outlet and the outlet maintains a reference to the view controller. All properties with weak references must be optional types and by definition must be a variable so that they can be set to nil.

here is a code sample.

19 — What does it mean to “capture self” in a closure and why can it lead to a memory leak?

Closures are reference types, and it’s implementation relies on capturing variables and the context they are defined in, when we use self inside a closure we are keeping a strong reference to it and in consequence, it can lead to a memory leak.

20 — What does inferred typing mean in Swift?

This means that Swift language infers type at compile time if you can from the objective C word you can tell that the difference is that in Objective-C you always need to provide the type for any property like this.

NSString *name = @”Sasha Blumenfeld”

In Swift, you just declare it like this and the compiler will infer the type

let name = “Sasha”

21 — What is an implicitly unwrapped optional?

An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a non-optional value.Because the value of an implicitly unwrapped optional is automatically unwrapped when you use it, there’s no need to use the ! operator to unwrap it. That said, if you try to use an implicitly unwrapped optional that has a value of nil, you’ll get a runtime error. So when to use it? …You should only ever mark a variable as an Implicitly Unwrapped Optional if you can guarantee that it will NOT be nil at the time it’s called.

22 — When casting, when would you use as? vs as!

The upcast, going from a derived class to a base class, can be checked at compile time and will never fail. However, downcasts can fail since you can’t always be sure about the specific class. If you have a UIView, it’s possible it’s a UITableView or maybe a UIButton. If your downcast goes to the correct type — great! But if you happen to specify the wrong type, you’ll get a runtime error and the app will crash.Like optionals, It’s better to use the as? because it will avoid your app to crash in case the object can’t be downcast.

23 — What are the correct ways to unwrap an optional value?

The best way to unwrap optional values is by optional binding and/or using guard statements,

Which one to use it will depend on your implementation, the if let will give you a constant variable that you can use inside the scope of the if let braces, the guard statement will give you a constant variable that you can use outside the scope of the guard braces and it will handle the error inside its own scope.

Here is a code sample

24 — What is optional chaining?

Working with optional values can feel a bit clumsy sometimes, and all the unwrapping and checking can become so onerous that you might be tempted to throw some exclamation marks to force unwrap stuff so you can get on with work.

Swift provides optional chaining, which lets you run code only if your optional has a value. For example…

Here is the example

25 — What is a property observer?

A property observer allows you to execute some code anytime a value is set or about to be set.

They are not called during the initialization, they are after you can add property observers to any stored property that is not lazy loaded.

they use the willSet and didSet keyword like so…

var value: Double = 0.0 {

//right before we change the value of the property

willSet {

print(“Old value: \(value)”)

}

//is called inmediatle after we assign a value to the stored property, after the value is assigned

didSet {

print(“New value: \(value)”)

}

}

26 — What is the difference between Objective-C and Swift for handling errors?

Swift can handle both, automatic and manual propagation of errors while, objective C can not. Objective- C handle errors by manual propagation only, checking the result for nil first, if nil check the error.

27 — What is the difference between weak and unowned, how you should use it?

Weak and unowned references enable one instance to refer to the other instance without keeping a strong hold on it, thereby avoiding reference cycles, we use a weak reference when the other instance that we’re holding onto has a shorter lifetime, that is when the instance being captured is deallocated first, for example in delegates in Swift or if you saw them in oBjective C you should tell that they are marked as a weak reference and that’s because the delegate can be nil out while the parent object still survives, in short words if the object being held on to, the weak one, has a shorter (or could have a shorter) lifetime than the parent object use weak. In other hand use unowned if both objects have the same lifetime, for example when you declare a closure as value for a property in a class and inside the closure you are capturing self, you should create a capture list for that closure mark as unowned, because in this case, the closure can’t exist without the class.

28 — What does the @escaping keyword mean?

In Swift 3 closures are marked as @noescape by default, sometimes completion handlers have to be marked by @escaping since they have executed some point after the enclosing function has been executed.

If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is escaping. It is also said that the closure argument escapes the function body.

29 — What are generics in Swift?

Swift language provides ‘Generic’ features to write flexible and reusable functions and types. Generics are used to avoid duplication and to provide abstraction. Swift standard libraries are built with generics code. Swifts ‘Arrays’ and ‘Dictionary’ types belong to generic collections. With the help of arrays and dictionaries, the arrays are defined to hold ‘Int’ values and ‘String’ values or any other types.

Here is a full example.

30 — What is Protocol oriented programming?

This is a very extensive topic and its impossible for me to resume it; instead, I want to share some links that will introduce you to the power of protocol-oriented programming.

Here is my code sample.

What the 55 Swift Standard Library Protocols Taught Me

Introducing Protocol-Oriented Programming in Swift 3

Practical protocol-oriented programming

One last note… I am not saying that you should switch completely to this language and bury your objective C knowledge, absolutely not, still the biggest companies like Facebook and Uber for mention a couple, are built on objective C and if you are lucky to have a chance to work for them, that knowledge will be very useful, but if your goal is to work for a young startup that wants to build a greenfield project, is very probable that they will do it on Swift.

I hope you find this post helpful, remember that these are just “pointers” to some topics and my intention is just to give a brief intro for each of them plus some code examples that you can use as cheat sheets for syntax purposes and some links to very great resources, there is sooo much more and in future posts I will share more…

It will be great if you can share Swift topics that you think are a “must know” for Junior devs!

Peace!