让你的Swift代码看起来更有逼格的技巧

最近把项目优化了一遍,用了一些语法糖,语法糖可以提高编程序效率,别人阅读代码的时候会觉得你的代码很工整,有逼格,也方便维护。下面展示一些最近的优化示例。

1、可选值拆包
优化前:
var nickName: String?
var userHederSrc: String?
//使用时
func setUserInfo(){
    if let nickName = nickName {
        if let userHederSrc = userHederSrc {
           print("nickName:\(nickName),userHederSrc:\(userHederSrc)")
        }
    }
}

宛如金字塔的层层嵌套,如果参数过多,简直无法想象。

guard优化后:
var nickName: String?
var userHederSrc: String?
//使用时
func setUserInfo(){
    guard let nickName = nickName, let userHederSrc = userHederSrc
        else { return }
    print("nickName:\(nickName),userHederSrc:\(userHederSrc)")
}
2、泛型是个好东西

去除数组中的重复的元素

优化前:

func removeStrSameElement(_ originArr: [String]) -> [String] {
    return originArr.reduce([String]()) { $0.contains($1) ? $0 : $0 + [$1] }
}
func removeIntSameElement(_ originArr: [Int]) -> [Int] {
    return originArr.reduce([Int]()) { $0.contains($1) ? $0 : $0 + [$1] }
}
// 打印结果:["a", "b", "d", "e", "c"]
print(removeStrSameElement(["a", "b", "a", "d", "e", "d", "b", "c"]))
// 打印结果:[1, 2, 3, 4, 5]
print(removeIntSameElement([1, 2, 3, 4, 2, 3, 5, 4]))

一种类型写一种,太累。

泛型优化后:
func removeSameElement<T: Equatable>(_ originArr: [T]) -> [T] {
    return originArr.reduce([T]()) { $0.contains($1) ? $0 : $0 + [$1] }
}
// 打印结果:["a", "b", "d", "e", "c"]
print(removeSameElement(["a", "b", "a", "d", "e", "d", "b", "c"]))
// 打印结果:[1, 2, 3, 4, 5]
print(removeSameElement([1, 2, 3, 4, 2, 3, 5, 4]))
3、按钮事件过多Selector优化

如果一个控制器里的Button特别的多,那添加Button点击事件的Selector 会觉得特别的臃肿。

优化前:
class example{

    lazy var button: UIButton = {
        let button = UIButton()
        button.addTarget(self, action:#selector(funcAClick), for: .touchUpInside)
        return button
    }()
    
    @objc func funcAClick(){
        print("exampleA:funcA")
    }
    ...
}
Selector优化后:

优化方法:扩展Selector,整洁,点语法用起来更方便

class exampleBase{
    
    lazy var button: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: .funcAClick, for: .touchUpInside)
        return button
    }()
    
    @objc func funcAClick(){
        print("exampleA:funcA")
    }
}
private extension Selector {
    static let funcAClick = #selector(exampleBase.funcAClick)
    ...
}
4、善用扩展

遍历多种类型数组

优化前:
var stringArray = ["A", "B", "C"]
var intArray = [1, 3, 4, 5, 6]
var doubleArray = [1.0, 2.0, 3.0]

func printStrArr(a: [String]) { for s in a { print(s) } }
func prIntArr(a: [Int]) { for i in a { print(i) } }
func printDoubleArr(a: [Double]) {for d in a { print(d) } }

printStrArr(a:stringArray)
prIntArr(a:intArray)
printDoubleArr(a:doubleArray)
扩展优化后:

短小精悍

var stringArray = ["A", "B", "C"]
var intArray = [1, 3, 4, 5, 6]
var doubleArray = [1.0, 2.0, 3.0]

extension Array{
    func printArray() { for s in self { print(s) } }
}
stringArray.printArray()
intArray.printArray()
doubleArray.printArray()
5、遍历之where

遍历寻找符合条件的元素

优化前:
let array = [1,2,3,4,5]
let dic = [1:"heihei1",2:"heihei1"]
for i in array{
    for j in dic.keys{
        if j  == i && dic[j] != nil {
            print(i)
        }
    }
}
where优化后:
let array = [1,2,3,4,5]
let dic = [1:"heihei1",2:"heihei2"]
for i in array where dic[i] != nil {
    print(i)
}
6、用枚举替换字符串

多用枚举替换字符串,字符串容易敲错

优化前:
switch season {
case "spring": print("spring: do something")
case "summer": print("summer: do something")
case "autumn": print("autumn: do something")
case "winter": print("winter: do something")
default: print("Fuck")
}
枚举优化后:
enum Season { case spring, summer, autumn,winter }
var season = Season.spring
switch season {
case .spring: print("spring: do something")
case .summer: print("summer: do something")
case .autumn: print("autumn: do something")
case .winter: print("winter: do something")
}
7、默认值 ??合并语句
优化前:
var userHeaderSrc: String?
var defaultSrc = "http://baidu.com"
var userUseSrc = ""

if let userSrc = userHeaderSrc { userUseSrc = userSrc } else
 { userUseSrc = defaultSrc }
??优化后:
var userHeaderSrc: String?
var defaultSrc = "http://baidu.com"
var colorToUse = userChosenColor ?? defaultColor
8、过滤器filter

筛选出能被2整除的值

优化前:
var newEvens = [Int]()
for i in 1...10 {
 if i % 2 == 0 { newEvens.append(i) }
}
print(newEvens) // [2, 4, 6, 8, 10]

过滤器(filter)可以更简单的实现,也使代码更整洁

filter优化后:
var evens = Array(1...10).filter { $0 % 2 == 0 }
print(evens) // [2, 4, 6, 8, 10]
9、找数组最大最小值

常规解法

优化前:
func minMax(arr:[Int])->(Int,Int) {
var min:Int = arr[0]
  var max:Int = arr[0]
  for i in 0..<arr.count {
      if arr[i] < min {
          min = arr[i]
      }
      if arr[i] > max {
          max = arr[i]
      }
  }
  return (min,max)
}
var findArr:[Int] = [100,5,6,8,3,7,9,10,0,40,1,2]
minMax(arr:findArr)

过滤器(filter)可以更简单的实现,也使代码更整洁

filter优化后:
var findArr:[Int] = [100,5,6,8,3,7,9,10,0,40,1,2]
 findArr.min()
 findArr.max()
10、闭包优化函数
优化前:
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 1, y: 1) // 2

不需要记住有关的名字和变量,只要一个$符号

filter优化后:
var sumBlock: (Int, Int) -> (Int) = { $0 + $1 }
sumBlock(1, 1) // 2

你可能感兴趣的:(Swift)