Professional Documents
Culture Documents
TECH
Written by Mathivathani Murugesan and Prasad NRV - 24 Sep 2017 3 minutes read
Swift is built with the open source LLVM compiler framework and has been included in Xcode since version
6. On platforms other than Linux, it uses the Objective-C runtime library which allows C, Objective-C, C++ and
Swift code to run within one program.
If you have just begun your Swift journey, here are some tips useful that will help improve your basic
standards in coding:
1. Extension:
// Okay Version
func square(x: Int) -> Int { return x * x }
square(x:squaredOFFive) // 625
The useless variable was created to double square 5— we need not enjoy typing.
// Better Version
extension Int {
5.squared // 25
5.squared.squared // 625
2. Generics:
// Bad Code
var stringArray = ["Twitter", "Facebook", "Instagram"]
// Awesome Code!
func printElementFromArray(a: [T]) {
// Okay Code
var i = 0
while 5 > i {
print("Count")
i += 1 }
You made the variable “i” to make sure your computer doesn’t break by printing limited numbers. Remember,
more variables = more memorization = more headache = more bugs = more life problems.
// Better Code
for _ in 1...5 { print("Count") }
4. Optional Unwrapping:
// Okay code
var myUsername: Double?
// Hideous Code
func userLogIn() {
if let username = myUsername {
print("Welcome, \(username)"!) } } }
// Pretty Code
func userLogIn()
else
{ return }
print("Welcome, \(username)!") }
The difference is tremendous. 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. No Pyramid.
// Okay Code
func getDiameter(radius: Double) -> Double { return radius * 2}
getDiameter(radius: 5) // return 10
You created two mutually exclusive functions. Outrageous! Let’s connect the dot between radius and
diameter.
// Good Code
var radius: Double = 10
radius // 10
diameter // 20
diameter = 1000
radius // 500
Now, the radius and diameter variables are interdependent of each other. More connections = less extra
typing = fewer typos = fewer bugs = fewer life problems.
These are some basic tips to become a better Swift developer. We hope this makes coding more easier
and swift, with fewer bugs and more productivity.
Do continue to read more tips for Swift development in Part 2 of this post!
torustech.co
BACK
4 minutes read
READ MORE
TECH
2 minutes read
READ MORE
TECH
4 minutes read
READ MORE
Privacy Policy
©2018 Torus Tech Co. - All Rights Reserved