Jump to content
  • Advertisement
  • entries
    6
  • comments
    0
  • views
    1057

10 Swift programming language tips for lazy-ass iOS developers

shahidmansuri

903 views

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.

Swift-code-review.jpg?itok=d3gDy5ll
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 {
print("Count")
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
 



0 Comments


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
  • Advertisement
  • Blog Entries

  • Similar Content

    • By LonelyStep
      PROGRESS
      Thought I'd reach out for some feedback on my little project. This is an android two-player game for top-down boxing matches. The core mechanics are all that I have accomplished thus far, later I want to add different configurations for your boxer (special effects, increased health or damage, etc) and maybe even a single player AI to practice against.

      SCREENSHOTS
      #1

      *****************************************************************

      #2
       
      FEEDBACK
      Right now the gameplay feedback I'm looking for is on the fundamental mechanics of the game.

      One area of particular concern is the window of opportunity for a player to block after their opponent has begun a punch. Currently that window is one-tenth of a second, otherwise you will be to late to counter their blow. I want it to be difficult to successfully pull off a block and have it be something that requires real attention to accomplish. I'm wondering though if it isn't too difficult right now, which may encourage mindless button mashing, which is certainly not what I want to condone.

      Another consideration is whether having three main actions (block, attack, charge) provides a good balance. My idea with having three main areas is that your two thumbs will have to leave one section uncovered at all times. This should result in hand movements that telegraph actions to the opponent.

      Aside from these, any other constructive criticism is very welcome.

      LINK
      My game can be found at the Google Play Store here:
      https://play.google.com/apps/testing/com.meatandgrain.PunchABunch

      NOTE There is a known graphics error when performing a special punch. There are no doubt other unknown errors as well.

        Thank you for your time, I hope you'll be able to find some fun in this little game!
    • By JustACicada
      Random Number God has been updated to v1.1.0.
      This is an incremental (although not idle) game about defeating randomized robots by rolling dice and playing cards that alter those dice and their effects.
      Other than performance fixes, the game has been rebalanced from the ground up. Now it should progress in a more fluid fashion. An option to reset the game with a significant boost to your power has been added, allowing you to advance further than you could before.
      There is also now an option to significantly speed up battle animations. Once you learn the rules of the game, a battle can easily take <2 min.
      Windows, Linux: https://justacicada.itch.io/random-number-god
      Android: https://play.google.com/store/apps/details?id=samuelVazquez.randomNumberGod


    • By Tenebris Equum
      i'm game designer without coding skills.
      i came here looking for Companions with Compassion; i must Retrieve mobile gaming industry overview.
      no matter where you live in this World; please step out it's about time. language barrier won't be problem between us.
      express your passion, and join me on this journey i'll talk to you about this Phenomenal project, add me on discord.
      startup is interesting, but im good.
      if this thread inappropriate please shut down the topic thanks.
    • By MiTi
      Dear everyone, this is my newest game, please check out and give me feedback. Thanks for your consideration.

      Overview: Cross n Puzz is a creative and addicting word puzzle game. It not only challenges your brain but also improve memory and other types of cognitive function.

      For IOS: https://itunes.apple.com/app/crossword-puzzle-image/id1435575074

      For Android: https://play.google.com/store/apps/details?id=com.caag.crosswordnpuzzle

      Game trailer: https://www.youtube.com/watch?v=stNuktpJH44&feature=youtu.be
      Crossword Puzzle Image Trailer Official.mp4  
    • By mtjscott
      Hey, so i've created a disk in unity (2D mobile) that will be shot forward if you drag it back and the further you drag it from the start point the more force will be applied to the impulse similar to the 8ball pool drag to shoot mechanic on miniclip. However, when I applied a script that allows the main camera to follow the ball it broke the mechanic since the balls position is calculated through the camera in world space. So I created a bool that locks the camera in place until the ball is released so the calculation would happen before the camera starts to move. This works however the ball now rubber bands back and forwards close to the start position.
       
      If anything needs more explaining then i'd be glad to do so. I've only been coding for about a week so you'll have to bare with me. Any help is appreciated. Thank you very much.
       
      Here's What happens:
      https://gyazo.com/f211e50f32ac59437a93dad7295a14be
      (screencap gif of the game viewer)
       
      Here is the shoot script:
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shoot : MonoBehaviour { [SerializeField] GameObject Disc; [SerializeField] float multiplier; Vector3 initPos; private Rigidbody2D rb; public static bool ballIsReleased = false; bool recordingDistanceDragged = false; private void Start() { rb = gameObject.GetComponent<Rigidbody2D>(); initPos = transform.position; } void OnMouseDrag() { recordingDistanceDragged = true; if(recordingDistanceDragged == true) { transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)); } else { transform.position = initPos; } } void OnMouseUp() { ballIsReleased = true; } private void FixedUpdate() { if(ballIsReleased == true) { rb.AddForce((initPos - transform.position) * multiplier, ForceMode2D.Impulse); Debug.Log("ball is released"); recordingDistanceDragged = false; } else { ballIsReleased = false; } } }  
      Here is the camera follow script:
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { private Vector2 velocity; public float smoothTimeY; public float smoothTimeX; public GameObject player; private void Start() { player = GameObject.FindGameObjectWithTag("Player"); } private void FixedUpdate() { if (Shoot.ballIsReleased == true) { Debug.Log("camera can move"); float posX = Mathf.SmoothDamp(transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX); float posY = Mathf.SmoothDamp(transform.position.y, player.transform.position.y, ref velocity.y, smoothTimeY); transform.position = new Vector3(posX, posY, transform.position.z); } } }  
×

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!