Learning Swift as Objective-C programmer — Basics

My personal note for catching up with the evolution of Swift from Objective-C part 1

As of now, the latest version of Swift is 3.0. I was so excited when Swift was announced at WWDC 2014. As time passed by, Swift slowly but certainly started to take over the main stream position for iOS app development.

It makes sense for some companies to continue using Objective-C if their main features are written in Objective-C, as mixing two languages will expand build size. And also some teams are taking advantage of C++ integration of the language.

However, as Swift is much more stable thanks to other developers, I don’t have strong reason not to learn the language. I believe there are some people trying to move out from Objective-C so I decided to summaries the diff that I needed to know to completely move away from the old friend.

This is going to be the first part of the long journy of Swift.

Diffs in Basics

Print

No more NSLog. You can use print function and use variables in strings directly.

let greeting = "Guten Morgen!"
let myName = "Yusuke"
print("\(greeting) Mine name ist \(myName))")

Strings

Handling strings is much simpler than Objective-C. If we want to append strings with Objective-C, it looked like this:

NSString *name = @"Swift";
NSString *greeting = [@"Hi! " stringByAppendingString:[NSString stringWithFormat:@"This is %@!", name];
NSLog(@"%@", greeting); // >
"Hi! This is Swift!"

With Swift:

let name = "Swift"
var greeting = "Hi! " + "This is \(name)!"
print(greeting) // > "Hi! This is Swift!\n"

Getting a subrange of a string is a bit more readable. With Objective-C we needed to use substringWithRange() and NSRange:

[name substringWithRange:NSMakeRange(1,2)];

subrange of a string can be obtained by below with Swift:

let start = str.index(str.startIndex, offsetBy: 1)
let end = str.index(str.startIndex, offsetBy: 3)
let range = start..<end
print(string.substring(with: range))

You can read more about why strings in Swift is more like collection here:

Tuples

Swift has tuples support.

let coordinates = (x:1.0, y:2.0)
print(coordinates.x) // > 1.0

Comparison

comparison has become so much simper as well.

let name1 = "Bob"
let name2 = "Tom"
print(name1 < name2) // > True

For loops

Now you can use range of numbers with for loops.

for i in 0..<10 {
print(i)
}

Not only that, you can add condition to for loops with where statement, as opposed to using if statement.

for i in 0..<10 where i % 2 == 0{
print(i)
}

Switch statements

Swift switch statements allow you to use not only numbers but strings. Let’s take a look at an example.

let name = "Bob"
switch name {
case "Bob":
print("Bob")
case "Tom":
print("Tom")
default:
print("Does not match.")
}

You can also use range of numbers, and conditions can be also specified with where statements.

let number = 9
switch number {
case 0...5:
print("0 to 5")
case let x where x == 6:
print("It's 6")
default:
print("Not defined")
}

Functions

Unlike most of functions in Objective-C, function parameters are constants by default in Swift. They are equivalent of constant declared with let. If we want to modify parameters in functions then you can use inout statement.

Optionals

This is a new concept for Objective-C programmers. It’s basically a box around certain type which allows us to use nil. I think most of you guys heard of that.

There are multiple ways to unwrap optionals but I think the most unfamilier way is optional binding.

let autherName: String? = nil
if let autherName = autherName {
print(autherName)
}

You can assign optional values to constant and use them in the if statement. It’s common to give the same name for unwrapped value as the optional value.

Another very Swifty way of unwrapping would be guard let.

func printNameIfExists(name: String?) {
guard let name = name else { return }
print(name)
}

guard let is not just about unwrapping but it’s more about the happy path.

func printNameIfExists(id: String) {
guard let name = name(id: id) {
print("No name found.")
return
}
print("Age of \(name) is \(age)")
}

With the example above, we want the name to be present but there might be some cases names won’t be found. By describing like this, it’s much easier for readers to understand what the happy path is.

Conclusion

I have covered basic concepts in Swift such as strings, control flows, and optionals. Xcode and auto complete made it so much easier as mentioned in a epsode of under the radar.

I will continue digging into the language with the next story.

References

Swift Apprentice — Great book for swift biginners.

The Swift Programming Language (Swift 3.1) — Apple’s document

Show your support

Clapping shows how much you appreciated Yusuke Kawanabe’s story.