10 Tips to become a better Swift Developer
Type less, read less, produce more | Update on May 14th, 2017
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 Versionfunc 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 Versionextension Int {
var squared: Int { return self * self }
}5.squared // 255.squared.squared // 625
2. Generics
Ex) Print all elements in an array
// Bad Codevar 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 Codefunc printElementFromArray<T>(a: [T]) { for element in a { print(element) } }
3. For Loop vs While Loop
Ex) Print “Count” 5 times
// Okay Codevar i = 0while 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 Codefor _ 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. 🤘
The content has been migrated from Medium to personal platform. You can read the rest of the content about the other 6 Swift tips here