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

10 Tips to become a better Swift Ninja🏴

This isn’t a part 2. You are now in a different league

Introduction

Again, please excuse me for the formatting. I tried to have it as concise as possible. Feel free to play around with Playground, and if you spot any problems, please comment below. I will fix it/them asap.

1. Convenient Initializers

Ex) Get a number of toes and fingers for a human

// Original Way
class Human {
  var finger: Int
  var toe: Int

  init(finger: Int, toe: Int) {
    self.finger = finger
    self.toe = toe
  }
}

var elon = Human(finger: 10, toe: 10)
elon.finger // 10
elon.toe // 10

Most humans have 10 fingers and toes. Don’t you input, pre-initialize.

// Cooler Way
class Human {
  var finger: Int
  var toe: Int
  init(finger: Int, toe: Int) {
    self.finger = finger
    self.toe = toe
  }
  convenience init() {
    self.init(finger: 10, toe: 10) // referring to the top init block
  }
}

var bill = Human()
bill.finger // 10
bill.toe // 10

2. Type Casting

Ex) Merge [Int] and [String] array into [Any]

When you make an API call from Facebook, you would receive a series of urls of profile pictures[String] and the number of likes[Int] for each.

You want to merge those two different types of arrays into a single array just for the sake of portability.

Remember, I explained the logic in the previous post.

fewer variables → fewer life issues (shorter version)

// Upcasting (as)
var likes = [123, 342, 231] as [Any]
var photos = ["Beach", "Girls", "Chill"] as [Any]
// merge them
for like in likes {
 photos.append(like) }
photos // ["Beach", "Girls", "Chill", 123, 342, 231]

You’ve upcasted the both arrays into Any. You’ve then merged them. As a result, you now carry everything in a single array, called, “photos”. That’s pretty handy, isn’t it?

Now, it’s time to downcast. In other words, time to convert from [Any] → [String] or [Int]

// Downcasting (as?)
for i in photos {
 if let number = i as? Int {
  print(number) } // 123, 342, 231

 if let string = i as? String {
  print(string) } // "Beach", "Girls", "Chill"
}

3. Switch Statement vs If-Else

Ex) Recommend healthy drinks for different age groups

Age Group

1-7: Milk

8-80: Soda

81-150: Water

Beyond: ??

// Aweful Code
var myAge = 20
if myAge >= 1 && myAge <= 7 {
 print("🍼")
} else if myAge >= 8 && myAge <= 80 {
 print("🍺")
} else if myAge >= 81 && myAge <= 150 {
 print("🚿")
} else {
 print("You alive, bruh?")
}

Stop repeating.

By the way, just to show some respect, I’ve researched and found the oldest person ever lived was 122 years 164 days according to Wikipedia

Anyway, stay focused.

// Beautiful Code
switch myAge {
 case 2...7: print("🍼")
 case 8...80: print("🍺") // X find the right emoji
 case 81...150: print("🚿")
 default: print("You alive, bruh?")
}

“Sweet, I love 🍺”— Bob

4. Function Custom Parameters

Ex) Print a traveller’s direction

Prints a traveller’s origin and destination

func getD(userOrgin: String, userDestination: String) {
 print("From \(userOrgin), to: \(userDestination)")}
getD(userOrgin: "🇺🇸", userDestination: "🇰🇷") // From 🇺🇸 to: 🇰🇷

5. Variadic Parameters

Ex) Find the mean from multiple inputs

So you want a function takes input values close to infinity?

Here you go. 👌

var total: Double = 0
func findTheMean(numbers: Double...) -> Double {

  for number in numbers { total += number }

  return total / Double(numbers.count) }

findTheMean(numbers: 1, 3, 5, 7, 11) // 5.4
findTheMean(numbers: 1, 4, 8, 16, 25) // 16.2
findTheMean(numbers: 111, 222, 333) // 249

6. EMOJI 👑

Ex) Inspiration

I use emoji often. It allows me to express my personality and character more than with my limited English.

How many times have you seen those boring, “foo”, “aClass”, “bClass”, “boo” examples?

Let’s just spice things up.

Again, I went off on a tangent. Focus.

// Traditional
func whatBobLoves(first: String, second: String) {
 print("I enjoy \(first), and love \(second) ") }

Teaching a 3-year old how to code in Swift 3

// 👶 Code
func tellMeWhatBobLoves(💛: String, 💙: String) {
 print("I enjoy \(💛), and love \(💙) ") }
tellMeWhatBobLoves(💛: "teaching", 💙: "community")

7. Functional Programming

Ex) Square numbers in an array

// Widely-known way
var firstFivePositiveInt: [Int] = []

for i in 1...5 { firstFivePositiveInt.append(i * i) }

print(firstFivePositiveInt) // [1, 4, 9, 16, 25]

Use “map”

let fiveNumbers = [Int](1...5)

let fiveSquaredNumbers = fiveNumbers.map { $0 * $0 }
fiveSquaredNumbers // [1, 4, 9, 16, 25]

8. Subscripts

Ex) Find shortcuts

// Normal way to access proprety
class DayOfWeek {
 var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
}

var dayOfWeek = DayOfWeek()
dayOfWeek.days[0] // “Sun”
dayOfWeek.days[1] // “Mon”

Faster way to access “Sun” and “Mon”.

// Cooler Way 🕶
class NewDayOfWeek {
 var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]

 subscript(index: Int) -> String {
  return days[index] }
}

var newdDayOfWeek = NewDayOfWeek()
newdDayOfWeek[0] // “Sun”
newdDayOfWeek[1] // “Mon”

9. Property Observers

Ex) Convert Fahrenheit to Celsius

// What 99% would do
var celsius = 0

func convertFToC(F: Double) -> Double {
 return (F - 32) * (5 / 9) }

convertFToC(F: 300) // 148.9

Again, need not create a function.

// willSet & didSet

var celsius: Double = 0
var fahrenheit: Double = 100 {
 willSet { print("You are about to convert") }
 didSet { celsius = (fahrenheit - 32) * (5 / 9) } }

fahrenheit = 300 // "You are about to convert"
celsius // 148.9

fahrenheit = 200 // "You are about to convert"
celsius // 93.3

“willSet” runs just right before the fahrenheit value is set. “didSet” runs only after the fahrenheit value has been set.

10. What’s your tip to become a Ninja?

Now, it’s your turn. I could have finished up the remaining 10% of the article. But, I also want to learn from you. Please share your secret sauce with this beloved community.🎙

“Iron sharpens iron”

Last Remarks

Since we’ve completed the purpose of this article, now I can fully express my deep appreciation and thankfulness for this community. I’ve been writing blog articles for the first time in my life. As you can tell, I’ve never been a writer. Tbh, I’ve never enjoyed writing. I’m 20. I had enough of 13 years of writing — with the only intention — to get that “A”. Now, it has changed. However, I wouldn’t say I still “love” writing. Writing is like talking. No one truly loves vibrating their vocal cords, but the impact and feeling one experiences from it. Again, This isn’t related to how to become a Swift ninja. However, I thought it was more important for me to be self-aware where I got started so that I can remain humble and maintain chillness by appreciating great gifts Medium and this iOS community have given me.

About Me

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