Here are some tips to help you become a better Swift developer by writing less code and performing better.
1. The Extension and expansion
Example: Square
// Okay Version
func square(x: Int) -> Int { return x * x }
var squaredOFFive = square(x: 5)
square(x:squaredOFFive) // 625
Copy the code
Create invalid variables, square 5 and then square again — we don’t like typing, after all.
// Better Version
extension Int {
var squared: Int { return self * self }
}
5.squared // 25
5.squared.squared // 625
Copy the code
2. Generics Generics
Example: Print all elements in an array
// Bad Code var stringArray = ["Bob", "Bobby", "SangJoon"] var intArray = [1, 3, 4, 5, 6] var doubleArray = [1.0, 2.0, PrintStringArray (a: [String]) {for s in a {print(s)}} [Int]) { for i in a { print(i) } } func printDoubleArray(a: [Double]) {for d in a { print(d) } }Copy the code
For many invalid functions, we only need to create one.
// Awesome Code
func printElementFromArray(a: [T]) {
for element in a { print(element) } }
Copy the code
3. For loop vs. While loop
// Okay Code
var i = 0
while 5 > i {
print("Count")
i += 1 }
Copy the code
Create the variable “I” to make sure your computer doesn’t crash printing limited numbers.
Remember: the more variables, the more memory, the more trouble, the more bugs, the more problems. The butterfly effect is something to remember
// Better Code for _ in 1... 5 { print("Count") }Copy the code
4. Selective expansion example: Gaurd let vs if let
Let’s write a program that welcomes new users.
var myUsername: Double? var myPassword: Double? // Hideous Code func userLogIn() { if let username = myUsername { if let password = myPassword { print("Welcome, \(username)"!) }}}Copy the code
Did you see the Armageddon pyramids? Nested code is a pain in the neck. Absolutely not! Take the bad code out and make it better.
// Pretty Code
func userLogIn() {
guard let username = myUsername, let password = myPassword
else { return }
print("Welcome, \(username)!") }
Copy the code
The difference between the two is obvious. If the username or password has a zero value, elegant code calls “return” to exit early. Otherwise, a welcome message appears.
5. Calculate properties vs functions
Example: find the diameter of a circle
// 💩 Code getDiameter(radius: Double) -> Double {return radius * 2} func getRadius(diameter: Double) Double) -> Double { return diameter / 2} getDiameter(radius: 10) // return 20 getRadius(diameter: 200) // return 100 getRadius(diameter: 600) // return 300Copy the code
Two mutex functions were created above. That’s too bad! We connect the point between the radius and the diameter.
// Good Code
var radius: Double = 10
var diameter: Double {
get { return radius * 2}
set { radius = newValue / 2} }
radius // 10
diameter // 20
diameter = 1000
radius // 500
Copy the code
Now, the radius and diameter variables are independent of each other. More connections → less extra input → fewer errors → fewer bugs → fewer problems.
Example: Selling tickets
// Simply Bad
switch "Adult" {
case "Adult": print("Pay $7")
case "Child": print("Pay $3")
case "Senior": print("Pay $4")
default: print("You alive, bruh?") }
Copy the code
“Adult”, “Child”, “Senior” → this is hard coding, typing out the strings for each case one by one, absolutely not. I’ve explained what can go wrong with writing too much. We don’t like typing at all.
// Beautiful Code
enum People { case adult, child, senior }
switch People.adult {
case .adult: print("Pay $7")
case .child: print("Pay $3")
case .senior: print("Pay $4")
default: print("You alive, bruh?") }
Copy the code
“.adult, “”.child,” “.senior “is definitely right. If the switch statement goes beyond the specified enumeration and encounters something unknown, with a red error () on the left, Xcode will alert. — I can’t find the right expression.
Invalid merger
Example: a user selects a Twitter theme color
// Long Code
var userChosenColor: String?
var defaultColor = "Red"
var colorToUse = ""
if let Color = userChosenColor { colorToUse = Color } else
{ colorToUse = defaultColor }
Copy the code
This code is too long. Let’s shorten it.
// Concise AF
var colorToUse = userChosenColor ?? defaultColor
Copy the code
If userChosernColor returns zero (invalid), select defaultColor (red); otherwise, select userChosenColor.
8. Conditional mergers
For example: SpikyHair is high
// Simply Verbose
var currentHeight = 185
var hasSpikyHair = true
var finalHeight = 0
if hasSpikyHair { finalHeight = currentHeight + 5}
else { finalHeight = currentHeight }
Copy the code
The code above is too long, let’s slim it down.
// Lovely Code finalHeight = currentHeight + (hasSpikyHair ? 5:0)Copy the code
The above code means that if hasSpikeHaire is true, the final height increases by 5; If it is false, the final height is increased by 0 (not increased).
9. Functional programming
Example: Get an even number
// Imperative (a.k.a boring) var newEvens = [Int]() for i in 1... 10 { if i % 2 == 0 { newEvens.append(i) } } print(newEvens) // [2, 4, 6, 8, 10]Copy the code
You don’t need to know the whole story. Review the for loop is a waste of time. It could be clearer.
// 😎 var evens = Array(1... 10).filter { $0 % 2 == 0 } print(evens) // [2, 4, 6, 8, 10]Copy the code
Functional programming is phenomenal and makes you smarter.
10. Closure vs Func
// Normal Function
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 5, y: 6) // 11
Copy the code
You don’t need to remember the names of functions and variables.
// Closure
var sumUsingClosure: (Int, Int) -> (Int) = { $0 + $1 }
sumUsingClosure(5, 6) // 11
Copy the code
Li Fa see from programmer inn
Original source: https://medium.com/ios-geek-community/10-tips-to-become-better-swift-developer-a7c2ab6fc0c2#.mj7165jnl