I heard that you have learned Swift for several months, do you have any idea to become a Swift master? Here I have 11 secret skills, donors and listen to me slowly, a good fate.
1. The Extension (Extension)
Task: find the square of numbers.
Func square(x: Int) -> Int {return x * x} var squaredOfFive = square(x: 5) square(x: 5) //Copy the code
To find 5 to the fourth power we were forced to create the variable squaredOfFive – experts don’t like being forced to define a useless variable.
// 下 载 extension Int {var squared: Int {return self * self}} 5. Squared // 25 5. SquaredCopy the code
2. The generic (up)
Task: Print out all the elements in the array.
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
How many functions have to be defined? Rookie can endure master can not endure!!
Func printElementFromArray(a: [T]) {for element in a {print(element)}}Copy the code
3. For traversal vs. While traversal
Task: Print Lujiazui 5 times
Var I = 0 while 5 > I {print(" I ") I += 1}Copy the code
I was forced to define variable I to ensure that lujiazui was printed 5 times. Note that the more variables defined, the more potential risks, the more life problems. This is the butterfly effect. Do you want X’s life to be disharmonious?
// For _ in 1... 5 {print(" print ")}Copy the code
The above code is really neat and beautiful.
4. Gaurd let vs if let
Task: Let’s write a program that welcomes new users.
var myUsername: Double? var myPassword: Double? Func userLogIn() {if let username = myUsername {if let password = myPassword {print(" Uniqlo welcome, \(username)"!) }}}Copy the code
This nasty nested code, we’re going to kill it
Func userLogIn() {guard let username = myUsername, let password = myPassword else {return} print(" \(username)!" )}Copy the code
Notice here if myUsername or myPassword nil, it’s going to end prematurely, otherwise it’s going to print uniqlo welcome, XXX.
5. Calculate properties vs functions
Task: Calculate the diameter of a circle
Func 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
Above we created two unrelated functions, but are diameters and perimeters really unrelated?
Var diameter: Double = 10 var diameter: Double { get { return radius * 2} set { radius = newValue / 2} } radius // 10 diameter // 20 diameter = 1000 radius // 500Copy the code
Now the radius and the diameter are interdependent, really reflecting the relationship between the two. Remember the butterfly effect? Fewer dependencies, cleaner code, fewer problems, better life!
6. Enumeration – Type safety
Task: Sell tickets
// Adult switch "Adult" {case "Adult": print(" print $50 ") case "Child": print(" print $50 ") case "Senior": Print (" Please pay $30 ") default: print(" Are you sure it's not a zombie, buddy?" )}Copy the code
“Adult,” “Child,” “Senior,” these are all hard-coded, you have to type in these characters manually each time, remember what we talked about above? The fewer manual typing, the fewer errors, and the better life.
// 高 级 版 enum People {case adult, child, senior} switch People. Adult {case. Adult: print(" please pay 50 yuan ") case. Print (" Please pay $25 ") case. Senior: print(" Please pay $30 ") default: print(" Are you sure it's not a zombie, buddy?" )}Copy the code
This way you avoid the error of typing, because “.adult “, “.child “, “.senior “are defined as enum’, and any instances that are not in the predefined range will be pointed out by Xcode.
7. Null conjunction operators
Task: the user chooses the main color of the microblog.
Var userChosenColor: String? var defaultColor = "Red" var colorToUse = "" if let Color = userChosenColor { colorToUse = Color } else { colorToUse = defaultColor }Copy the code
This is too bloated. Let’s lose some weight.
Var colorToUse = userChosenColor?? defaultColorCopy the code
To explain a little bit, if userChosenColor is nil, select defaultColor, otherwise userChosenColor. In fact, the null conjunction operator is a short representation of the following code.
a ! = nil ? a! : bCopy the code
8. Functional programming
Task: Get even numbers.
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
This for loop is tedious and makes you sleepy.
Var evens = (1... 10).filter { $0 % 2 == 0 } print(evens) // [2, 4, 6, 8, 10]Copy the code
Do you feel like functional programming makes you look smarter?
9. Closures vs functions
Task: Find the sum of two numbers.
Func sum(x: Int, y: Int) -> Int {return x + y} var result = sum(x: 5, y: 6) // 11Copy the code
I also need to remember function names and variable names for this function, right? Can we have one less?
Var closure: (Int, Int) -> (Int) = {$0 + $1} sumUsingClosure(5, 6) // 11Copy the code
10. Attribute observer
Task: Calculate the diameter of a circle
Var radius = 10.0 func parsed (radius: Double) -> Double {return radius * 2} parsed (radius: Double) radius) // return 20Copy the code
You don’t have to define a function here.
Var diameter = 0 var diameter: Double = 10 {willSet {print(" diameter ")} didSet {diameter =radius * 2}} radius = 10Copy the code
WillSet is called before assigning radius to the variable, while didSet is called after assigning RADIUS to the variable.
11. Facilitate initialization
Task: How many fingers and toes a person has
Class Human {var finger: Int var toe: Int init(finger: Int, toe: Int) Int) { self.finger = finger self.toe = toe } } var daDi = Human(finger: 10, toe: 10) daDi.finger // 10 daDi.toe // 10Copy the code
Since most people have ten fingers and toes, they can be pre-assigned at initialization.
// class Human {var finger: Int var toe: Int init(finger: Int, toe: Int) Int) { self.finger = finger self.toe = toe } convenience init() { self.init(finger: 10, toe: }} var daDi = Human() dadi.finger // 10 dadi.toe // 10Copy the code
The convenience keyword can be added to the init initialization method in Swift, which is mainly used for convenience.
All the convenience initializers must call the top-level initializer in the same class for initialization. In addition, the initialization method of convenience cannot be overridden by subclasses or called super from subclasses.
Eleven skills told, finished work.
PS: In fact, there are Switch vs if-else, variable parameters, etc., because this article is translated and sorted out in the two articles 1 and 2, I will not repeat it here. If you are interested, you can check the original text.
Recommended reading:
Swift, JSON and ObjectMapper