here to share some of the help you become more excellent Swift Developer's advice to make your code, write less, better performance , easy to play with Swift development .
1. Extension Extension
Example: Square
Okay Versionfunc square(x:int), Int { return x * x}var squaredoffive = Square (x:5)
Square (x:squaredoffive)//625
Create an invalid variable, and then square the 5 squared -- We don't like typing after all.
Better Versionextension Int {
var squared:int { return self * self}
}5.squared//255.squared.squared//625
2. Generics generics
Example: printing all the elements in an array
Bad Codevar stringarray = ["Bob", "Bobby", "Sangjoon"]var intarray = [1, 3, 4, 5, 6]var doub Learray = [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)}}
For many invalid functions, we just need to create one.
Awesome Codefunc printelementfromarray(A: [T]) {
for element in a {print (element)}}
3. For loop vs while Loop
Example: Print 5 times "Count"
Okay Codevar i = 0 While 5 > I {print ("Count")
i + = 1}
Create the variable "I" to make sure that your computer prints a limited number of digits without crashing.
Remember: More variables → more memory → more trouble →bug → more problems. The butterfly effect should be remembered
Better Code for _ in 1...5 {print ("Count")}
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 Codefunc userlogin() {
if let username = myusername {
if let password = mypassword {
Print ("Welcome, \ (username)"!)
}
}
}
Did you see the end of the world pyramid? Nested code is so annoying. Don't be resolute! Remove the bad code and change it to the better.
Pretty Codefunc userlogin() {
Guard Let username = myusername, let password = mypassword
Else { return }
Print ("Welcome, \ (username)!")}
The difference between the top and bottom is obvious. If the user name or password has a value of 0, the graceful code calls "return" to exit early. Otherwise, a welcome message will appear.
5. Calculate attribute vs function
Example: Finding the diameter of a circle
: Hankey:codefunc getdiameter(radius: Double) -> double { return radius * 2}func Getradius(diameter: Double) -> double {return Diameter / 2}getdiameter(radius: Ten)//returnGetradius( Diameter: $)//returnGetradius(diameter: +)//return 300
Two mutex functions are created above. It's too bad! We connect the points between the radius and the diameter.
Good Codevar radius:double = tenvar diameter:double {
Get { return radius * 2}
Set {radius = NEWVALUE/2}}
Radius//10
Diameter//20
diameter = 1000
Radius//500
now, the radius and diameter variables are independent of each other. More connections → fewer extra inputs → fewer →bug errors → fewer problems.
6. Type-Safe enumeration
Example: Ticketing
Simply Badswitch "adult" {
Case "Adult": Print ("Pay $7")
Case ' Child ': print ("Pay $")
Case "Senior": Print ("Pay $4")
default: Print ("You Alive, Bruh?")}
"Adult", "Child", "Senior" → this is in hard-coded, one after the other to each case of the string out, absolutely not. As explained above, there is nothing wrong with writing too much. We don't like to type at all.
Beautiful Codeenum people { case adult, child, senior}switch people.adult {
Case-Adult:print ("Pay $7")
Case-Child:print ("Pay $")
Case-Senior:print ("Pay $4")
default: Print ("You Alive, Bruh?")}
". Adult", ". Child", ". Senior" are sure to be correct. If the switch statement exceeds the range of the specified enumeration and encounters some unknown condition, a red error () on the left sidecausesXcode to alert. -- can't find the right expression.
7. Invalid Merge
Example: User Selection Twitter Theme Colors
Long Codevar userchosencolor:string? var defaultcolor = "Red"var colortouse = "" if let color = userchosencolor {Colortouse = color } Else
{colortouse = DefaultColor}
The code is too long, let's cut it down a bit.
Concise AFvar colortouse = Userchosencolor?? DefaultColor
The above code means that if userchoserncolor returns a value of 0 (not valid), select defaultcolor (red), otherwise, select Userchosencolor.
8. Conditional Merger
Example: Comb head ( Spikyhair) significantly higher
Simply Verbosevar currentheight = 185var hasspikyhair = Truevar finalheight = 0if h Asspikyhair {finalheight = currentheight + 5}
Else {finalheight = currentheight}
The code above is too long and we're going to give it a thin body.
Lovely Code
Finalheight = Currentheight + (hasspikyhair ? 5:0)
The above code means that if the Hasspikehaire is true, the final height increases by 5,and if it is false, the final height is added to 0(not incremented).
9. Functional Programming
Example: Get even
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]
no need to understand the whole process. Review The For loop above is a waste of time, in fact can be more clear.
Declarative:sunglasses:var evens = Array(1...10). filter {2% = = 0} print(evens)//[2, 4, 6, 8, 10]
Functional programming is a phenomenon-level program that makes you smarter.
Ten. Closure vs Func
Normal Function func sum(X:int, y:int), Int { return x + y}var result = SUM (X:5, y: 6)//11
You do not need to remember the names of functions and variables.
Closurevar sumusingclosure: (int, int)--(int) = {$ + $}
Sumusingclosure (5, 6)//11
Source: Internet technology and stuff.
10 tips to be a good swift developer