Have you been developing with Swift for months? Now, do you want to be a better Swift developer? Young man, you have come to the right place. I have a Wulin secret script that has been lost for many years to teach you. Don't care about the format of the code. I want to keep the code as concise as I can. So that you can easily copy it to playground for code verification.
No more nonsense, let's start a Swift experience happily.
1,Extension
Square
1. Normal version
func square(x: Int) -> Int { return x * x } var squaredOFFive = square(x: 5) square(x:squaredOFFive) // 625
2. Advanced version
extension Int { var squared: Int { return self * self } } 5.squared // 25 5.squared.squared // 625
summary
1. Normal version: if you want to square the same number multiple times, you also need to create redundant local variables, and the code is redundant.
2. Advanced version: add an extension to Int, and then add a calculation attribute to Int in the extension. In this way, the square value can be obtained without creating redundant local variables.
2,Generics
1. Normal version
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) } }
2. Advanced version
func printElementFromArray<T>(a: [T]) { for element in a { print(element) } }
summary
1. Normal version: each type must define a function, but the functions of each function are the same, resulting in code redundancy.
2. Advanced version: only one function is defined, and each type can be used.
3,For Loop vs While Loop
Output "Count" 5 times
1. Normal version
var i = 0 while 5 > i { print("Count") i += 1 }
2. Advanced version
for _ in 1...5 { print("Count") }
summary
1. When we don't need to use variables in the loop, we can use For Loop and_ Instead of While Loop.
2. Remember: the more variables - > the more problems - > the more bugs.
4,Optional Unwrapping
Gaurd let vs if let (new user login logic)
1. Normal version
var myUsername: Double? var myPassword: Double? // Hideous Code func userLogIn() { if let username = myUsername { if let password = myPassword { print("Welcome, \(username)"!) } } }
2. Advanced version
func userLogIn() { guard let username = myUsername, let password = myPassword else { return } print("Welcome, \(username)!") }
Translator's note:
//The above common version can also be written in this form if let username = myUsername, let password = myPassword { print("Welcome, \(username)"!) }
summary
1. The common version code structure is nested and redundant, and the advanced version is more clear at a glance.
2. It is recommended to use guard let when judging some prerequisites and necessary conditions.
5,Computed Property vs Function
Calculated diameter
1. Normal version
//Code 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 //translator's note var radi = 10.0 var dia = getDiameter(radius: radi) // 20 dia = 30.0 // 30 radi // 10.0 here, the value of radius must be changed by calling the getRadius function
2. Advanced version
// 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
summary
1. Normal version: two mutual conversion functions are created, the code is redundant, and there is no internal relationship between radius and diameter. When you modify the diameter, the corresponding radius is not modified.
2. Advanced version: realize the internal logical correlation between the two by calculating the attributes. When the diameter changes, the radius will change accordingly.
6,Enum to Type Safe
Buy a ticket
1. Normal version
switch person { case "Adult": print("Pay $7") case "Child": print("Pay $3") case "Senior": print("Pay $4") default: print("You alive, bruh?")}
2. Advanced version
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") }
summary
1. Ordinary version: hard coding is used to judge the string, which is difficult to maintain and the code readability is not high. It is possible to miss a condition and cause a bug.
2. Advanced version: create enum to realize all conditions. When you miss a case in the switch, the compiler will prompt an error and force you to judge all cases. This can reduce bug s and make the code more robust.
7,Nil Coalescing
Select color
1. Normal version
var userChosenColor: String? var defaultColor = "Red" var colorToUse = "" if let Color = userChosenColor { colorToUse = Color } else { colorToUse = defaultColor }
2. Advanced version
var colorToUse = userChosenColor ?? defaultColor
summary
use?? Set the default value of optional type variables to reduce redundant codes.
8,Conditional Coalescing
Calculate height
1. Normal version
// Simply Verbose var currentHeight = 185 var hasSpikyHair = true var finalHeight = 0 if hasSpikyHair { finalHeight = currentHeight + 5} else { finalHeight = currentHeight }
2. Advanced version
// Lovely Code finalHeight = currentHeight + (hasSpikyHair ? 5: 0)
summary
Reduce the amount of code and make the logic clearer through the ternary operator.
9,Functional Programming
Get even value
1. Normal version
// 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]
2. Advanced version
var evens = Array(1...10).filter { $0 % 2 == 0 } print(evens) // [2, 4, 6, 8, 10]
summary
Use filter instead of for loop above. It is also recommended that you use more high-order functions.
10,Closure vs Func
1. Normal version
// Normal Function func sum(x: Int, y: Int) -> Int { return x + y } var result = sum(x: 5, y: 6) // 11
2. Advanced version
// Closure var sumUsingClosure: (Int, Int) -> (Int) = { $0 + $1 } sumUsingClosure(5, 6) // 11