- Extension: Ex)Square a number
// Okay Version
func square(x: Int) -> Int { return x * x }
var squaredOFFive = square(x: 5)
square(x:squaredOFFive) // 625
The useless variable was created to double square 5— we need not enjoy typing. 创建了无用的中间变量
// Better Version
extension Int {
var squared: Int { return self * self }
}
5.squared // 25
5.squared.squared // 625
- Generics (泛型): Ex) 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, 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) } }
Too many useless functions. Let’s create just one. 太多的无用方法
// Awesome Code
func printElementFromArray<T>(a: [T]) {
for element in a { print(element) }
}
- For Loop vs While Loop: Ex) Print “Count” 5 times
// 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 Listen, more variables → more memorization → more headache → more bugs → more life problems.
// Better Code
for _ in 1…5 { print(“Count”) }
- Optional Unwrapping: Ex) Gaurd let vs if let Let’s make a program for welcoming a new user.
var myUsername: Double?
var myPassword: Double?
// Hideous Code
func userLogIn() {
if let username = myUsername {
if let password = myPassword {
print(“Welcome, \(username)”!)
}
}
}
Do you see the pyramid of doom 调用地狱/ 末日金字塔
// Pretty Code
func userLogIn() {
guard let username = myUsername, let password = myPassword else { return }
print(“Welcome, \(username)!”)
}
The difference is trendemous. 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. 🤘 不同是显而易见的,如果用户名或密码为空,会提前退出,否则会打印欢迎信息。没有金字塔
- Computed Property vs Function: Ex) finding a diameter of a circle
// 💩 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
You created two mutually exclusive functions. Atrocious. Let’s connect the dot between radius and 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
Now, the radius and diameter variables are interdependent of each other. More connections → less extra typing → fewer typos → fewer bugs → fewer life problems. 💅 现在,半径和直径变量是相互依赖的。更多的连接—更少的额外输入—更少的打字—更少的错误—更少的生活问题。💅
- Enum to Type Safe: Ex) Ticket Selling
// Simply Bad
switch person {
case “Adult”: print(“Pay $7”)
case “Child”: print(“Pay $3”)
case “Senior”: print(“Pay $4”)
default: print(“You alive, bruh?”)
}
“Adult”, “Child”, “Senior” → you are hard coding. You are literally typing all these string values for each case. That’s a no no. I explained what happens when you write too much. We never enjoy typing. “成人”、“孩子”、“年长”→你是硬编码。您实际上是为每种情况键入所有这些字符串值。这是不可能的。我解释了当你写太多时会发生什么。我们从不喜欢打字。
// Beautiful Code
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”)
}
You will never make a typo because “.adult”, “.child”, “.senior” highlight themselves. If the switch statement encountered unknown cases beyond the scope of the designated enum, Xcode would scream with that red error (😡) on the left side. — I just couldn’t find the right emoji. 你永远不会犯错误,因为”“会高亮突出自己。如果开关语句遇到未知的情况下超出了指定的枚举的范围,Xcode会报错。 7. Nil Coalescing (nil 合并): Ex) User choosing Twitter theme color
// Long Code
var userChosenColor: String?
var defaultColor = “Red”
var colorToUse = “”
if let Color = userChosenColor { colorToUse = Color } else
{ colorToUse = defaultColor }
Too long. Let’s cut the fat.
// Concise AF
var colorToUse = userChosenColor ?? defaultColor
The code above states, if userChosenColor returns nil, choose defaultColor (red). If not, choose userChosenColor.
- Conditional Coalescing (有条件的合并):
Ex) Increase height if you have spiky hair
// Simply Verbose
var currentHeight = 185
var hasSpikyHair = true
var finalHeight = 0
if hasSpikyHair { finalHeight = currentHeight + 5}
else { finalHeight = currentHeight }
Too long, cut the fat.
// Lovely Code
finalHeight = currentHeight + (hasSpikyHair ? 5: 0)
The code above states, if hasSpikeHair is true, add 5 to the final height, if not add zero.
- Functional Programming (函数式编程): Ex) Get even numbers
// 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]
I don’t need to see the entire process. I am wasting my time reviewing how your for-loop looks like. Let’s make it explicit. 我不需要看到整个过程。我在浪费时间回顾你的for循环是什么样子的。让我们明确一点。
// Declarative 😎
var evens = Array(1…10).filter { $0 % 2 == 0 }
print(evens) // [2, 4, 6, 8, 10]
Functional Programming is phenomenal. 函数式编程是非凡的
- Closure vs Func
// Normal Function
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 5, y: 6) // 11
You need not memorize the name of the function and the variable — You just need one. 你不需要记住函数和变量的名字——你只需要记住一个。
// Closure
var sumUsingClosure: (Int, Int) -> (Int) = { $0 + $1 }
sumUsingClosure(5, 6) // 11