• entries
6
0
• views
939

10 Swift programming language tips for lazy-ass iOS developers

836 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.

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.

}
}
}

Abolish the bad, bring the good with Guard let

else { return }
}

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 getRadius(diameter: Double) -> Double { return diameter / 2}

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 diameter: Double {
get { return radius * 2}
set { radius = newValue / 2}
}

diameter // 20
diameter = 1000

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

There are no comments to display.

Create an account

Register a new account

• Similar Content

• Continuing to work on “Eldest Souls” (first article here!), I’ve begun familiarising myself with the workflow between Fmod and Unity, and the integration system. I know much of this will be pretty obvious to most, but I thought I’d share my thoughts as a complete beginner learning the ropes of sound designing.
The library of sounds that Fmod provides has been very useful, at least as reference points. I’ve still kept to my ethos of producing the sounds myself as much as possible. Having said that, Fmod gives you 50 free sounds with your download, and I’ve used a wooden crate smash, a drawbridge and electricity sound you can hear in the foley video below.

The thing i found most useful was witnessing changes i made in Fmod being realised instantly in Unity. If a volume needed changing, or the timing of one of my effects was off, i can literally switch to Fmod and then back to Unity and immediately see the result of my alterations. It also seems apparent that using middleware such as this (or i've heard Wwise is also equally intuitive) grants the developer, and myself included, a great deal more flexibility and opportunity to edit sounds without going all the way back to a DAW, and bouncing down again. Needless to say, my workflow is so much faster because of it.
I've also loved the randomised feature of Fmod, whereby any sound can be made to sound slightly different each time it is heard. Taking a footstep recording i made for example, I was able to add further authenticity of uneven footsteps by randomising the pitch and volume of each playback.

I used this technique when creating footsteps for the first major boss in the game called "The Guardian". A big, over-encumbered husk of a monster. I also had fun rummaging through the garage for old tools and metal components for the “Guardian” (the first boss) footsteps. See below!

I also created a sword attack for our player, trying to sound different from the generic “woosh” I see in so many video games. I used a very “sharp” and abrasive sound to differentiate him from any enemies.

On another note, I recently upgraded my microphone to a Rode NTG2 shotgun, which has been phenomenal. I haven’t had to worry about noise interfering with the clarity of my objects, whereas before with the sm58 I had to be clever with my EQ and noise reduction plugins.
Important to note again that this still a “cheap” mic in comparison to most other products on the market, and all in all my entire setup is still very simple and affordable which I’m quite proud of. I’ve seen many musicians spend heaps of money on gear they don’t necessarily need. I much prefer being resourceful with less equipment, than to have more than I can understand or remember how to use.
It’s forced me to understand every aspect and capability of my tools, which I believe is a principal that can be applied to any discipline.

I have more fun little sound effect videos on my Instagram for those interested, where I post regular updates. Thanks for reading! (if you’ve made it this far)

www.sergioronchetti.com
INSTAGRAM
fallenflagstudio.com

• BASICS IN SOUND DESIGNING FOR VIDEO GAMES

Recently I joined the talented team at Fallen Flag Studio as the composer for their latest release "Eldest Souls" which consequently lead me into a field I have always dreamt of trying - sound design!
Having no prior experience, I began watching a few online tutorials (if you want to learn from anyone make it Akash Thakkar from "Hyper Light Drifter"... what a guy!) and basically just testing stuff out i found around the house. Luckily my dad has a garage FULL of random crap to use.
Before i continue, it's important to note that i DO NOT have fancy equipment, meaning anyone can try this. (my equipment is an sm58, focusrite scarlett interface and Logic Pro X plugins... that's it!)
I started basic with some footsteps, which weren't all too difficult. Then I moved on to projectiles and a spear attack one of the bosses has. Below are a couple super short videos on my resulting attempts.

Amazing how great a banjo sounds for that typical "woosh" sound! And if you're wondering, the paper was added to give some texture to the jab.
I could be finding a lot of these sounds in libraries online (like the built-in ones that come with Fmod and Unity) but I've chosen not to, in order to produce authenticity and hopefully a more unique gameplay experience for players when the final product is put together.

P.S. if you'd like to try the game and hear my hard work we'll be at EGX and several other conventions later this year, soon to be announced! Thanks for reading!
www.sergioronchetti.com
fallenflagstudio.com

To those interested, there's an Alpha trailer of the game in question below.

• By Gafami
Dear community,
I would like inform you that "War IOM" v2 have been re-work graphics and added more feature to serve user experience.
Here is my banner screenshot:

++++ Game description:
The rule to win the game is very simple: buy the soldiers, defeat the enemy army and then destroys the flag. Try to use fireball to wipe out the enemy.
Game data be stored on both user's device and server so never lost data again.

++++ Here is the look and feel of War IOM icon on your Home-screen phone

Rumor: You can get double gem receive if you beat the mini boss at level 3. Also win level 3 will give you a lot of Gem, use it to buy new solider and upgrade your army!

/******** Change log update 08/26 ********/
-- Add new game play for level 6.

-- Improve camera.
-- Improve game performance.
/******** Change log update 08/31 ********/
/******** Change log update 19/09 ********/
-- Add level 7 with new game play.
Regards,
Gafami

• Hi, this is my first finished game ever.
It took my 2 years because Im little bit lazy.
Its simple game where you defend the castle agains random spawned enemies. Lots of flying physics objects included :).
What do you think?
Video

• Hello, and thanks for taking the time to read my post.

I am not here asking for someone to do my work for me. I am just looking for a mentor who would not mind answering a few of my questions, and give me a little guidance.

I prefer chatting on discord, so if you are interested in helping me get started, please add me. My username is wize1 @8135
×