Swift Developer

Swift Developer

Type less, read less, produce more

  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

  1. 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

  1. 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”) }
“Gorgoeus” — Bob

For Loop Lesson

  1. 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. 🤘

  1. Computed Property vs Function

Ex) finding a volume of a box

// 💩 Code
func getVolume(width: Double) -> Double { return width * 3 }
func getWidth(volume: Double) -> Double { return volume / 3 }
getVolume(width: 10) // return 30
getWidth(volume: 300) // return 100
getVolume(width: 600) // return 1800
You created two mutually exclusive functions. Atrocious. Let’s connect the dot between volume and width.

// Good Code
var width: Double = 10
var volume: Double {
get { return width * 3 }
set { width = newValue / 3 } }
width // 10
volume // 30
volume = 1000
width // 333.3
Now, the volume and width variables are interdependent of each other. More connections → less extra typing → fewer typos → fewer bugs → fewer life problems. 💅

  1. Enum to Type Safe

Ex) Ticket Selling

// Simply Bad
switch “Audlt” {
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 }
switch People.adult {
case .adult: print(“Pay $7”)
case .child: print(“Pay $3”)
case .senior: print(“Pay $4”)
default: print(“You alive, bruh?”) }
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

  1. Nil Coleasing

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.

  1. Conditional Coleasing

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.

  1. 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.

  1. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s