Jump to content
  • Advertisement
  • entries
  • comments
  • views

10 Swift programming language tips for lazy-ass iOS developers



If you have worked on somebody else’s project, you know how hard it is to makes sense of long blocks of complicated codes not written by you. There were many reasons Apple introduced Swift Programming Language in 2014 to replace Objective-C, Apple’s primary programming language since 1996. The main reason was getting a piece of work done without the programmer having to write long lines of codes and raise readability of the program written. For example, Swift, unlike Objective C, supports functional programming, doesn’t need instance variables and to state the type explicitly, and has the ability to map raw value to enum directly. Swift is, indeed, the iOS development language for lazy developers.
Of course, Swift supports the traditional programming paradigms based on the rules of mathematics like any other languages. Sometimes, developers have no option but to use them. However, most of the time, Swift programmers can do away with fewer lines of code. 
I will validate my point with a few code examples:

1.       Swift extensions are a life saver

Long, boring codes make an already tough job of a programmer, tougher.
For example, writing a program to square a number makes Swift look such an average programming language, it is not in the code example below.

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

As I said, Swift makes way for smaller, concise code. In this example, the credit goes to Swift extensions. Squaring a number seems like a cakewalk.
extension Int { 
 var squared: Int { return self * self }
5.squared // 25
5.squared.squared // 625

Did you know unlike Objective-C categories, Swift extensions do not have name?

2.    Use Generics and avoid creating unnecessary functions
Three functions and three variables are an overblow to write such a minuscule program. Swift doesn’t seem to add any value to the programmer in the following code example.
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) } }

With generics, you can write the above example with a single function in Swift.
func printElementFromArray<T>(a: [T]) {
 for element in a { print(element) } }

3.    Use For loop when you want to use While loop
While loops are unnecessarily long to write. A single loop to count numbers from 1 to 5 doesn’t have to be 4 lines long.
var i = 0
while 5 > i {
i += 1 }

For loops are a complete bliss in Swift. The example below will clear you doubts if you had any.
for _ in 1...5 { print("Count") }

4.    Use Guard let, not if let
If let leads to hideous codes. A pyramid of doom is a big no-no in programming, at least with Swift as the language to develop iOS apps.
Look at the code example to welcome new users. Those are nasty nested code.
var myUsername: Double?
var myPassword: Double?

func userLogIn() {
 if let username = myUsername {
  if let password = myPassword {
   print("Welcome, \(username)"!)

Abolish the bad, bring the good with Guard let
var myUsername: Double?
var myPassword: Double?

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

5.    Exclusive functions vs dependent function
You can create two mutually exclusive functions or you can connect between them if you’re looking to write smaller codes.
The following code example finds the diameter of a circle using two exclusive functions.
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

However, when the radius and diameter variables dependent on each other, you will make 
more connections, type less, make fewer typos, result in fewer bugs and thus rarer instances of programming blunders.

var radius: Double = 10

var diameter: Double {
 get { return radius * 2}
 set { radius = newValue / 2}

radius // 10
diameter // 20
diameter = 1000
radius // 500

6.    Enum to Type Safe

“Adult”, “Child”, “Senior”. You are not supposed to do hard coding in Swift. The least, there mustn’t arise an event when you have type all these string values for each case, over and again. That’s a big no. Don’t do that, please.

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

When you write too much, you lose track and end up making mistakes. Did I mention, Swift has the ability to map raw value to enum directly. Let’s leverage on it.

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 typographical error because “.adult”, “.child”, “.senior” will highlight themselves in the Apple’s IDE. 

7.    If let is hard to get by

If let is something you’re going to encounter in every language. The advantage with Swift is you can skip it more often than other programming languages.
For example, the code below helps users choose Twitter theme color.

var userChosenColor: String?
var defaultColor = "Red"
var colorToUse = ""

if let Color = userChosenColor { colorToUse = Color } else
 { colorToUse = defaultColor }

I can cut the code. This is going to change your life as a programmer.

var colorToUse = userChosenColor ?? defaultColor

If userChosenColor returns nil, choose defaultColor (red). If not, choose userChosenColor. As simple as that. 

8.    Conditional Coalescing

Hair spike increases your height by a couple of inches. So I tried to write a code to solve the problem, except against Swift convention I used three variable and if else in my code. Will god forgive me?

var currentHeight = 185
var hasSpikyHair = true
var finalHeight = 0

if hasSpikyHair { finalHeight = currentHeight + 5}
 else { finalHeight = currentHeight }

I am a god-fearing programmer and have utmost respect for the Apple’s primary programming language. So I compacted the code above my measures. This is how it looks now. 

finalHeight = currentHeight + (hasSpikyHair ? 5: 0)

The code above states, if hasSpikeHair is true, add 5 to the final height, if not add zero. May the force be with you.

  • The power of Functional Programming

Among many reasons Apple replaced Objective C with Swift as its primary programming languge, one was Objective C’s alienation with functional programming. I have written the program below in Swift as I would have in Objective C that lacks functional programming. The code looks lousy, doesn’t it?

var newEvens = [Int]()

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

A simple function will get me rid of the For loop and if let (I hate it) and will reduce the entire code to two lines. Just take a look back and see how much time you wasted writing for-loop. Let’s make the code explicit. Ingenious, isn’t it?

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

Functional Programming is prodigious.
Functional Programming separates shrewd programmers from everyday programmers.

  • Closure vs Func

This is how a normal function looks like in in Swift. I mean this looks a fine piece of code.

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

However, who wants to remember the name of the function and the variable when you can do away with remembering either a function or variable. I chose variable in this case:

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

Love your code and it is gonna love you back


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!