AppleiOS App DevelopmentMobile DevelopmentswifttipsXcode

Swift Tips for iOS Developers

5/5

Swift is the best assistant to start an exciting journey of iOS development. If you’re an aspiring iOS programmer, then the first steps in this programming language will be pleasant and clear. Contrary, if you are an experienced Objective-C coder, Swift will make you forget about Objective-C forever.

Though the battle between these two languages still exists, the obvious winner is Swift. If you still hesitate, read our previous article Swift VS Objective-C: What to Choose in 2018?

It doesn’t matter if you’re a junior, middle or senior iOS developer, there is always something new to learn. Therefore, we decided to share some tips on how to become better Swift developer than you are today.

  1. Experiment and Validate with the Playground
  2. Improve the Readability of Constants
  3. Optional Unwrapping
  4. Functional Programming
  5. Enumeration in Swift

TOP 5 iOS Development Tips for everyone

Experiment and Validate with the Playground

A playground is an interactive coding environment for Swift. Swift developers can create playgrounds when they need to test and validate a new idea, learn new Swift features or share their ideas and concepts with other developers. Even if you don’t plan to run a new project, open Xcode and create a playground for fun. The playground is exceptionally helpful if you’ll need to integrate a new payment method into your app.

Here is a small guide to playground creation in Xcode.

xcode for ios development

You can create a playground directly on the Xcode launch.

Or, create it from inside the Xcode.

xcode playground

Once you create a playground, you can start coding!

Improve the Readability of Constants

Swift makes it easy to utilize structs by adding all the constants of an app into a single file. Now iOS developers can group structures the following way:

import Foundation

struct Constants {

    struct BaseAPI {

        static let url = "https://api.google.com/"

        static let version = "v1"

    }

    struct FacebookAPI {

        static let url = "https://graph.facebook.com/"

        static let version = "v2.12"

    }

}

Nesting structures like this are used to assign a namespace to constants. For instance, Constants.FacebookApi.BaseUrl can be used to access Facebook’s BaseUrl constant.

Optional Unwrapping

Generally, if let is used to unwrap optional values safely, but it works only if there is a value. If the value is absent, the code block won’t run. A guard statement, on the other hand, aims to transfer program control out of scope when one or more conditions aren’t met. As a result, these guard statements make the code more readable and comprehensible. In turn, readability is what makes code easy to maintain. Especially when you’re dealing with large enterprise-grade apps or have a team of developers that is working on it.

Here is how you can create a new user:

let emailField = UITextField()
emailField.text = "abcd@mail.com"
let usernameField = UITextField()
usernameField.text = "vineet"
let passwordField = UITextField()
passwordField.text = "123456"
let conifrmPasswordField = UITextField()
conifrmPasswordField.text = "123456"

And now let’s see the difference between using if let and guard let.

if let example (or how you SHOULD Not do)

func loginIfLet(){
    if let email = emailField.text {
        if let username = usernameField.text {
            if let password = passwordField.text {
                if let conifrmPassword = conifrmPasswordField.text {
                    if password == conifrmPassword {
                        print("Email - (email)")
                        print("Username - (username)")
                        print("Password - (password)")
                    } else {
                        print("Password didn't match with conifrm password.")
                    }
                } else {
                    print("Conifrm password is empty.")
                }
            } else {
                print("Password is empty.")
            }
        } else {
            print("Username is empty.")
        }
    } else {
        print("Email is empty.")
    }
}
loginIfLet()

guard let example (or how you SHOULD do)

func loginGuardLet(){
    guard let email = emailField.text else {
        print("Email is empty.")
        return
    }
    guard let username = usernameField.text else {
        print("Username is empty.")
        return
    }
    guard let password = passwordField.text else {
        print("Password is empty.")
        return
    }
    guard let conifrmPassword = conifrmPasswordField.text else {
        print("Conifrm password is empty.")
        return
    }
    if password == conifrmPassword {
        print("Email - (email)")
        print("Username - (username)")
        print("Password - (password)")
    } else {
        print("Password didn't match with conifrm password.")
    }
}
loginGuardLet()

Now you can spot the difference and understand why guard let is better than if let.

Functional Programming

Functional programming considers computations to be the evaluation of mathematical functions. At the same time, it tends to avoid changing-state and mutable data. That means coding without side effects and changes of value in variables. The opposite paradigm is imperative programming allowing the change of state. In other words, a variable (a symbol) that is once assigned (value binding), doesn’t change its value.

The state is not eliminated in functional programming, it’s just made visible and explicit. By the way, in this type of programming, functions are literally mathematical functions. Meaning the output depends on the inputs.

As a result, you get the cleaner code. Since the defined variables stay not modified, there is no need to follow the change of state to understand how functions, methods classes or the whole projects are working.

Moreover, by using functional programming, you get the referential transparency. For instance, it’s possible to replace expressions by their values. Also, when a function with the same parameters is called, the output will be the same.

Check out the example of how to print all the even numbers from 1 to 10:

The old approach (DON’T use it)

var evenNumbers = [Int]()
for number in 1...10 {
    if number % 2 == 0 {
        evenNumbers.append(number)
    }
}
print(evenNumbers) //prints "[2, 4, 6, 8, 10]"

The new approach (DO use it)

var evens = Array(1...10).filter { (num) -> Bool in
    return num % 2 == 0
}
print(evens) //prints "[2, 4, 6, 8, 10]"

Or

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

Enumeration in Swift

Enumeration in Swift means collecting related values in groups to further work with them in a type-safe way within the code.

Example of a code without Enum ( bad code)

let directionToHead = "east"
switch directionToHead {
case "north":
    print("Lots of planets have a north")
case "south":
    print("Watch out for penguins")
case "east":
    print("Where the sun rises")
case "west":
    print("Where the skies are blue")
default:
    print("Unknown direction")
}
//prints "Where the sun rises"

Example of a code with Enum (good code)

enum CompassPoint {
    case north, south, east, west
}
let direction: CompassPoint = .east

switch direction {
case .north:
    print("Lots of planets have a north")
case .south:
    print("Watch out for penguins")
case .east:
    print("Where the sun rises")
case .west:
    print("Where the skies are blue")
}


Conclusion

We can say with no doubt that Swift is the number 1 programming language for iOS development nowadays. It has too many advantages to be included in one article. The advice we showed in this text is only the tip of the iceberg.

Not a developer but want to have an iOS app for your business? We have an experienced iOS team!

5/5
Sign up for the latest Altamira news

Take the next step

Let’s build your custom solution together!

Get an estimate of your futer project with all risks included.

Explore our Success Stories

See more works we are proud off. 

This site is registered on wpml.org as a development site.