Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

10 Best Tips to Swift Development from Swift expert

$
0
0

1. For Loop vs While Loop

Example: Print “Count” 5 times

// Okay Code 
var i = 0 
while 5 > i {
   print("Count :\(i)”) 
   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.

// 😍 Code

for i in 1...5 {
 print("Count  :\(i)”)
}

2. Optional Unwrapping

Example: Guard let vs if let

Let’s make a program for welcoming a new user.

var username: String?
var password: String?

// Hideous Code
func userLogIn() {
 if let uName = username {
  if let pwd = password {
   print("Welcome, \(uName)"!)
  }
 }
}

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 uName = username, let pwd = password 
  else { return } 
 print("Welcome, \(uName)!") 
}

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.

3. Extension

Example: Square a number

// Okay Version
func square(x: Int) -> Int { return x * x }
var squaredOfSix = square(x: 6)
square(x: squaredOfSix) // 625

The useless variable was created to double square 6— we need not enjoy typing.

// 😎 Version

extension Int { 
 var squared: Int { return self * self }
}

6.squared // 36
6.squared.squared // 1296

4. Generics

Example: Print all elements in an array

// 👿 Code

var arrString   = [“John Cena", “Tom Cruise", “Kristen Stewart"]
var arrInt		 = [4, 5, 6, 7, 8]
var arrDouble 	 = [6.0, 8.0, 10.0]

func printStringArray(arr: [String])
  for str in arr { 
    print(str) 
  } 
}

func printIntArray(arr: [Int]) {
  for i in arr {
    print(i)
  } 
}

func printDoubleArray(arr: [Double]) {
  for d in arr {
     print(d) 
  }
 }

Too many useless functions. Let’s create just one.

// 😍 Code

func printElementFromArray(arr: [T]) {
  for element in arr { 
    print(element)  
  } 
}

5. Functional Programming

Example: Get even numbers

// Imperative 
var arrEvens : [Int] = []
for i in 1…20 {
 if i % 2 == 0 { arrEvens.append(i) } }
print(arrEvens) // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

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…20).filter { $0 % 2 == 0 } 
print(evens) // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Functional Programming is phenomenal.
Functional Programming makes you look smart.

6. Closure vs Func

// Normal Function 
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 6, y: 8) // 14

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(6, 8) // 14

7. Computed Property vs Function

Example: 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: 20) // return 40

getRadius(diameter: 400) // return 200

getRadius(diameter: 800) // return 400

You created two mutually exclusive functions. Atrocious. Let’s connect the dot between radius and diameter.

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

radius // 20

diameter // 40

diameter = 8000 

radius // 4000

Now, the radius and diameter variables are interdependent of each other. More connections → less extra typing → fewer typos → fewer bugs → fewer life problems. 💅

8. Enum to Type Safe

Example: Ticket Selling

// Simply Bad

switch person {
 case "Adult": print("Pay $12”)
 case "Child": print("Pay $4”)
 case "Senior": print("Pay $8”)
 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.

// 👌 Code
enum People { case adult, child, senior }
var person = People.adult
switch person {
 case .adult: print("Pay $12”)
 case .child: print("Pay $4”)
 case .senior: print("Pay $8”)
}

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.

9. Nil Coalescing

Example: User choosing Twitter theme color

// Long Code
var userChosenColor: UIColor? 
var defaultColor = UIColor.red
var colorToUse = UIColor.clear
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.

10. Conditional Coalescing

Example: Increase height if you have spiky hair

// Simply Verbose
var currentHeight = 160
var hasSpikyHair = true
var finalHeight = 0
if hasSpikyHair { finalHeight = currentHeight + 5} 
 else { finalHeight = currentHeight }

Too long. Let’s 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.

Sandeep Joshi

Sandeep Joshi | iOS Developer

I’m Sandeep Joshi - an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App Development company. I am ambitious and intensely interested in what I do. You'll quickly find that I do not merely develop software - I develop highly maintainable, elegant code that will save you enormous sums in the long run.

Viewing all articles
Browse latest Browse all 595

Trending Articles