CloseHomeAboutBlogContactCourse
Bob I’m an iOS instructor/blogger from S.Korea.July 14 • 5 min read • Edit

10 Tips to become a better Swift Developer

Type less, read less, produce more

Introduction

*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 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) }
}

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

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.

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

Last Remarks

I understand I only covered handful ways to become a better Swift developer. Now, if you want to learn more advanced concepts such as Error handling, memory management, advanced enums, protocols, and closures, feel free to join my course called Learn Swift with Bob. If you wish to receive a private discount link, feel free to sign up here.

About Me

iOS Developer from South Korea. Feel free to follow my story on Instagram or get serious on LinkedIn