10 Tips to become a better Swift Developer

Type less, read less, produce more

Not my desk

So, you’ve been around with Swift for a couple of months. Now, you want to become a better Swift Developer? DRY, KISS, and not WET? I’ve got golden nuggets here and there for you.

Excuse me for the formatting, I tried to have as fewer lines as possible for conciseness. Feel free to copy and paste into Playground to check if everything works. 👊 If not, please comment below. I will fix them asap.

I have also embedded YouTube lessons under each part for an explanation.

I talked too much. Let’s get started.

1. Extension

Ex) Square a number

// Okay Version
func square(x: Int) -> Int { return x * x }
var squaredOFFive = square(x: 5)
square(x:squaredOFFive) // 625

The useless variable was created to double square 5— we need not enjoy typing.

// Better Version
extension Int { 
var squared: Int { return self * self }
}
5.squared // 25
5.squared.squared // 625

Extension Lesson

2. Generics

Ex) Print all elements in an array

// Bad Code
var stringArray = ["Bob", "Bobby", "SangJoon"]
var intArray = [1, 3, 4, 5, 6]
var doubleArray = [1.0, 2.0, 3.0]
func printStringArray(a: [String]) { for s in a { print(s) } }
func printIntArray(a: [Int]) { for i in a { print(i) } }
func printDoubleArray(a: [Double]) {for d in a { print(d) } }

Too many useless functions. Let’s create just one.

// Awesome Code
func printElementFromArray<T>(a: [T]) {
 for element in a { print(element) } }

Generic Lesson

3. For Loop vs While Loop

Ex) Print “Count” 5 times

// Okay Code
var i = 0
while 5 > i {
print("Count")
i += 1 }

You made the variable “i” to make sure your computer doesn’t break by printing limited numbers

Listen, more variables → more memorization → more headache → more bugs → more life problems.

Remember the Butterfly effect.

// Better Code
for _ in 1...5 { print("Count") }

“Gorgeous” — Bob

For Loop Lesson

4. Optional Unwrapping

Ex) Gaurd let vs if let

Let’s make a program for welcoming a new user.

var myUsername: Double?
var myPassword: Double?
// Hideous Code
func userLogIn() {
if let username = myUsername {
if let password = myPassword {
print("Welcome, \(username)"!)
}
}
}

Do you see the pyramid of doom? Those are nasty nested code. Never. Destroy the bad, bring the good.

// Pretty Code
func userLogIn() {
guard let username = myUsername, let password = myPassword
else { return }
print("Welcome, \(username)!") }

The difference is trendemous. If username or password has a nil value, the pretty code will early-exit the function by calling “return”. If not, it will print the welcoming message. No Pyramid. 🤘

5. Computed Property vs Function

Ex) finding a diameter of a circle

// 💩 Code
func getDiameter(radius: Double) -> Double { return radius * 2}
func getRadius(diameter: Double) -> Double { return diameter / 2}
getDiameter(radius: 10) // return 20
getRadius(diameter: 200) // return 100
getRadius(diameter: 600) // return 300

You created two mutually exclusive functions. Atrocious. Let’s connect the dot between radius and diameter.

// Good Code
var radius: Double = 10
var diameter: Double {
get { return radius * 2}
set { radius = newValue / 2} }
radius // 10
diameter // 20
diameter = 1000
radius // 500

Now, the radius and diameter variables are interdependent of each other. More connections → less extra typing → fewer typos → fewer bugs → fewer life problems. 💅

6. Enum to Type Safe

Ex) Ticket Selling

// Simply Bad

switch person {
case "Adult": print("Pay $7")
case "Child": print("Pay $3")
case "Senior": print("Pay $4")
default: print("You alive, bruh?") }

“Adult”, “Child”, “Senior” → you are hard coding. You are literally typing all these string values for each case. That’s a no no. I explained what happens when you write too much. We never enjoy typing.

// Beautiful Code
enum People { case adult, child, senior }
var person = People.adult
switch person {
case .adult: print("Pay $7")
case .child: print("Pay $3")
case .senior: print("Pay $4")
}

You will never make a typo because “.adult”, “.child”, “.senior” highlight themselves. If the switch statement encountered unknown cases beyond the scope of the designated enum, Xcode would scream with that red error (😡) on the left side. — I just couldn’t find the right emoji.

Switch Statement Lesson

Enum Lesson

7. Nil Coalescing

Ex) User choosing Twitter theme color

// Long Code
var userChosenColor: String? 
var defaultColor = "Red"
var colorToUse = ""
if let Color = userChosenColor { colorToUse = Color } else
{ colorToUse = defaultColor }

Too long. Let’s cut the fat.

// Concise AF
var colorToUse = userChosenColor ?? defaultColor

The code above states, if userChosenColor returns nil, choose defaultColor (red). If not, choose userChosenColor.

8. Conditional Coalescing

Ex) Increase height if you have spiky hair

// Simply Verbose
var currentHeight = 185
var hasSpikyHair = true
var finalHeight = 0
if hasSpikyHair { finalHeight = currentHeight + 5} 
else { finalHeight = currentHeight }

Too long, cut the fat.

// Lovely Code
finalHeight = currentHeight + (hasSpikyHair ? 5: 0)

The code above states, if hasSpikeHair is true, add 5 to the final height, if not add zero.

9. Functional Programming

Ex) Get even numbers

// Imperative (a.k.a boring)
var newEvens = [Int]()
for i in 1...10 {
 if i % 2 == 0 { newEvens.append(i) } }
print(newEvens) // [2, 4, 6, 8, 10]

I don’t need to see the entire process. I am wasting my time reviewing how your for-loop looks like. Let’s make it explicit.

// Declarative 😎
var evens = Array(1...10).filter { $0 % 2 == 0 } 
print(evens) // [2, 4, 6, 8, 10]

Functional Programming is phenomenal.

Functional Programming makes you look smart.

10. Closure vs Func

// Normal Function 
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 5, y: 6) // 11

You need not memorize the name of the function and the variable — You just need one.

// Closure
var sumUsingClosure: (Int, Int) -> (Int) = { $0 + $1 }
sumUsingClosure(5, 6) // 11 

Sweet

Closure Lesson


Last Remarks

I understand I only covered handful ways to become a better Swift developer. If I get 100 likes, I will make a Part 2. If you cared enough to finish reading the article, hit that ❤️for me so more people can find this article, and, of course, I feel loved and write better ones for you guys. :)


ps. Oh no. Part 2 is now available here. Please show me some love by joining me at my Facebook page 👍


If you have golden nuggets, please share with the community and a special shout-out to those who left thoughtful and meaningful contribution to the community! Silviu St, Diego Polcel, Peter Witham. Victor Tong, Oren Alalouf, Poonati Giri, Wilson Balderrama. Feel free to follow them because they care and show appreciation for others!

I feel thankful to interact and emerge myself in this phenomenal community with tremendous iOS Developers all around the globe. See you this Saturday!




Swift Conference

One of my Portuguese friends João, is organizing a Swift conference at Aveiro, Portugal. Unlike many ones out there, he designed this conference to be experimental and engaging. Audience gets to interact and build along with speakers — Bring your laptops guys. It’s my first Swift conference. I’m super excited! On top of that, it is affordable as well. The event will happen on June 1–2, 2017. If you are interested in knowing more, feel free to check out its website here or Twitter below.

My Upcoming Course (Update Feb 23th, 2017)

For the past 3 months, I have been creating an intermediate Swift course called, The UIKit Fundamentals with Bob. on Udemy. This course is designed for anyone who has played with iOS with Swift or Objective-C for 3–6 months. You do not take this course just to build apps. In fact, you can just copy off from Github. The goal is to understand the iOS ecosystem so that you gain the ability to catch fish and build your own empire. I plan to charge the course at $50 — I wll not let Udemy discount my course for any reason. If you are interested in knowing more and reserve your spot for free until the released date, shoot me an email at bobleesj@gmail.com I will give you a form and more info about the course.

Bob the Developer

Personal Update (Facebook Page) | Engagement (Twitter) | Personal Documentation (Instagram) | Tutorials & Vlog (YouTube) | Daily Diary (Website)